// DOM 元素缓存
const moduleContent = document.getElementById('module-content');
const logoutBtn = document.getElementById('logout-btn');
const menuItems = document.querySelectorAll('.sidebar li');
const currentUsername = document.getElementById('current-username');
const menuGroups = document.querySelectorAll('.menu-group h3');
const sidebar = document.querySelector('.sidebar');
const sidebarToggle = document.getElementById('sidebar-toggle');

// 初始化函数
function init() {
    // 为侧边栏菜单项添加点击事件
    menuItems.forEach(item => {
        item.addEventListener('click', function() {
            // 移除其他菜单项的激活状态
            menuItems.forEach(m => m.classList.remove('active'));
            
            // 激活当前点击的菜单项
            this.classList.add('active');
            
            // 加载相应的模块内容
            loadModuleContent(this.getAttribute('data-module'));
        });
    });
    
    // 为菜单组标题添加点击事件（折叠/展开功能）
    menuGroups.forEach(header => {
        header.addEventListener('click', function() {
            const targetId = this.getAttribute('data-target');
            const targetMenu = document.getElementById(targetId);
            const toggleIcon = this.querySelector('.toggle-icon');
            
            // 切换子菜单的折叠状态
            targetMenu.classList.toggle('collapsed');
            toggleIcon.classList.toggle('collapsed');
            
            // 保存菜单状态到localStorage
            saveMenuState();
        });
    });
    
    // 检查用户登录状态
    checkLoginStatus();
    
    // 设置用户名
    setCurrentUser();
    
    // 恢复菜单折叠状态
    restoreMenuState();
    
    // 为退出按钮添加点击事件
    const logoutBtnEl = document.getElementById('logout-btn');
    if (logoutBtnEl) {
        logoutBtnEl.addEventListener('click', function(event) {
            // 阻止默认行为
            event.preventDefault();
            // 清除所有用户会话数据
            localStorage.removeItem('user');
            sessionStorage.removeItem('user');
            // 使用 replace 跳转到登录页，替换历史记录
            window.location.replace('login.html');
        });
    }
    
    // 侧边栏展开/收缩功能
    if (sidebarToggle) {
        sidebarToggle.addEventListener('click', toggleSidebar);
        
        // 从本地存储中恢复侧边栏状态
        const sidebarState = localStorage.getItem('sidebarCollapsed');
        if (sidebarState === 'true') {
            sidebar.classList.add('collapsed');
        }
    }
    
    // 激活库存盘点预警模块（如果请求查看）
    const inventoryModule = document.querySelector('[data-module="inventory-management"]');
    if (inventoryModule) {
        inventoryModule.click();
    }
}

// 切换侧边栏展开/收缩状态
function toggleSidebar() {
    sidebar.classList.toggle('collapsed');
    
    // 保存侧边栏状态到本地存储
    localStorage.setItem('sidebarCollapsed', sidebar.classList.contains('collapsed'));
}

// 检查用户登录状态
function checkLoginStatus() {
    const user = JSON.parse(localStorage.getItem('user') || sessionStorage.getItem('user') || 'null');
    if (!user) {
        // 未登录，重定向到登录页
        window.location.href = 'login.html';
    }
}

// 设置当前用户信息
function setCurrentUser() {
    const user = JSON.parse(localStorage.getItem('user') || sessionStorage.getItem('user') || 'null');
    if (user && currentUsername) {
        currentUsername.textContent = user.username || '管理员';
    }
}

// 加载模块内容
function loadModuleContent(moduleName) {
    // 显示加载状态
    moduleContent.innerHTML = '<div class="loading">加载中...</div>';
    
    // 根据模块名称加载不同内容
    switch(moduleName) {
        case 'inventory-management':
            loadInventoryManagement();
            break;
        case 'product-input':
            loadProductInput();
            break;
        case 'promotion':
            loadPromotionManagement();
            break;
        case 'category':
            loadCategoryManagement();
            break;
        case 'price':
            loadPriceManagement();
            break;
        case 'warehouse-info':
            loadWarehouseManagement();
            break;
        case 'stock-in':
            loadStockInManagement();
            break;
        case 'stock-out':
            loadStockOutModule();
            break;
        case 'checkout':
            loadCheckoutModule();
            break;
        case 'report':
            loadSalesStatisticsModule();
            break;
        case 'cost':
            loadCostModule();
            break;
        case 'tax':
            loadTaxModule();
            break;
        // 添加新的模块处理
        case 'member-register':
            loadModuleFromHTML('member-register');
            break;
        case 'member-points':
            loadModuleFromHTML('member-points');
            break;
        case 'staff-info':
            loadModuleFromHTML('staff-info');
            break;
        case 'attendance':
            loadModuleFromHTML('attendance');
            break;
        case 'salary':
            loadModuleFromHTML('salary');
            break;
        case 'supplier-info':
            loadModuleFromHTML('supplier-info');
            break;
        case 'purchase-order':
            loadModuleFromHTML('purchase-order');
            break;
        case 'logs':
            loadModuleFromHTML('logs');
            break;
        case 'settings':
            loadModuleFromHTML('settings');
            break;
        default:
            // 默认显示欢迎界面
            loadWelcomeScreen();
    }
}

// 加载欢迎界面
function loadWelcomeScreen() {
    moduleContent.innerHTML = `
        <div class="welcome-screen">
            <h2>欢迎使用超市管理系统</h2>
            <p>请在左侧菜单选择需要管理的模块</p>
            
            <div class="dashboard">
                <div class="dashboard-item">
                    <h3>今日销售</h3>
                    <p class="dashboard-value" id="today-sales">¥0.00</p>
                </div>
                <div class="dashboard-item">
                    <h3>待处理订单</h3>
                    <p class="dashboard-value" id="pending-orders">0</p>
                </div>
                <div class="dashboard-item">
                    <h3>销售商品数</h3>
                    <p class="dashboard-value" id="sold-items">0</p>
                </div>
                <div class="dashboard-item">
                    <h3>库存预警</h3>
                    <p class="dashboard-value" id="inventory-alerts">0</p>
                </div>
            </div>
        </div>
    `;
    
    // 获取并更新最新的销售统计数据
    updateDashboardStats();
    
    // 获取库存预警数量
    fetch('/api/inventory-stats')
        .then(res => res.json())
        .then(response => {
            if (response.success) {
                document.getElementById('inventory-alerts').textContent = response.data.warning_count || '0';
            }
        })
        .catch(err => {
            console.error('获取库存预警数据失败:', err);
        });
}

// 加载库存盘点预警模块
function loadInventoryManagement() {
    moduleContent.innerHTML = `
        <div class="inventory-alert">
            <h2>库存盘点预警</h2>
            <div class="alert-cards">
                <div class="alert-card">
                    <div class="alert-icon alert-blue">
                        <i>📦</i>
                    </div>
                    <div class="alert-info">
                        <div class="alert-number" id="total-products">0</div>
                        <div class="alert-label">总商品数</div>
                    </div>
                </div>
                <div class="alert-card">
                    <div class="alert-icon alert-orange">
                        <i>⚠️</i>
                    </div>
                    <div class="alert-info">
                        <div class="alert-number" id="warning-products">0</div>
                        <div class="alert-label">库存预警</div>
                    </div>
                </div>
                <div class="alert-card">
                    <div class="alert-icon alert-red">
                        <i>❗</i>
                    </div>
                    <div class="alert-info">
                        <div class="alert-number" id="outofstock-products">0</div>
                        <div class="alert-label">缺货商品</div>
                    </div>
                </div>
            </div>
            <div class="action-bar">
                <div class="search-bar">
                    <select id="category-filter" class="search-select">
                        <option value="all">全部分类</option>
                    </select>
                    <select id="status-filter" class="search-select">
                        <option value="all">全部状态</option>
                        <option value="normal">正常</option>
                        <option value="warning">预警</option>
                        <option value="outofstock">缺货</option>
                    </select>
                    <input type="text" id="product-search" class="search-input" placeholder="搜索商品或编号">
                    <button id="search-inventory-btn" class="search-btn">
                        <i>🔍</i>
                    </button>
                </div>
            </div>
            <table class="inventory-table">
                <thead>
                    <tr>
                        <th>商品编号</th>
                        <th>商品名称</th>
                        <th>分类</th>
                        <th>当前库存</th>
                        <th>库存预警下限</th>
                        <th>库存状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="inventory-list">
                    <tr>
                        <td colspan="7" class="loading">加载中...</td>
                    </tr>
                </tbody>
            </table>
        </div>
    `;
    // 拉取统计数据和商品数据
    Promise.all([
        fetch('/api/inventory-stats').then(res => res.json()),
        fetch('/api/inventory-products').then(res => res.json()),
        fetch('/api/categories').then(res => res.json())
    ]).then(([statsResponse, productsResponse, categoriesResponse]) => {
        if (!statsResponse.success || !productsResponse.success || !categoriesResponse.success) {
            throw new Error('获取数据失败');
        }
        // 更新总览
        document.getElementById('total-products').textContent = statsResponse.data.total_products;
        document.getElementById('warning-products').textContent = statsResponse.data.warning_count;
        document.getElementById('outofstock-products').textContent = statsResponse.data.out_of_stock_count;
        // 填充分类筛选下拉框
        const categoryFilter = document.getElementById('category-filter');
        if (categoryFilter) {
            const categories = categoriesResponse.data;
            categories.forEach(category => {
                categoryFilter.innerHTML += `<option value="${category.name}">${category.name}</option>`;
            });
        }
        // 渲染表格
        updateInventoryProductTable(productsResponse.data);
        // 绑定筛选事件
        document.getElementById('search-inventory-btn').addEventListener('click', searchInventoryProducts);
        document.getElementById('category-filter').addEventListener('change', searchInventoryProducts);
        document.getElementById('status-filter').addEventListener('change', searchInventoryProducts);
        document.getElementById('product-search').addEventListener('keyup', function(e) {
            if (e.key === 'Enter') {
                searchInventoryProducts();
            }
        });
    }).catch(err => {
        const tableBody = document.getElementById('inventory-list');
        if (tableBody) {
            tableBody.innerHTML = `<tr><td colspan="7" class="error-message">加载失败：${err.message}</td></tr>`;
        }
    });
}

function updateInventoryProductTable(productList) {
    const tableBody = document.getElementById('inventory-list');
    if (!tableBody) return;
    if (!productList || productList.length === 0) {
        tableBody.innerHTML = '<tr><td colspan="7" class="no-data">暂无商品数据</td></tr>';
        return;
    }
    tableBody.innerHTML = '';
    productList.forEach(item => {
        let statusClass = '';
        switch(item.status) {
            case '缺货': statusClass = 'status-danger'; break;
            case '预警': statusClass = 'status-warning'; break;
            default: statusClass = 'status-normal';
        }
        tableBody.innerHTML += `
            <tr data-code="${item.product_code}">
                <td>${item.product_code}</td>
                <td>${item.product_name}</td>
                <td>${item.category}</td>
                <td>${item.current_stock}</td>
                <td>${item.min_stock !== null && item.min_stock !== undefined ? item.min_stock : '-'}</td>
                <td><span class="status-tag ${statusClass}">${item.status}</span></td>
                <td><button class="operation-btn btn-edit-threshold" data-code="${item.product_code}">编辑阈值</button></td>
            </tr>
        `;
    });
    document.querySelectorAll('.btn-edit-threshold').forEach(btn => {
        btn.addEventListener('click', function() {
            const code = this.getAttribute('data-code');
            editInventoryAlertByProductCode(code);
        });
    });
}

function searchInventoryProducts() {
    const categoryFilter = document.getElementById('category-filter');
    const statusFilter = document.getElementById('status-filter');
    const productSearch = document.getElementById('product-search');
    if (!categoryFilter || !statusFilter || !productSearch) return;
    const category = categoryFilter.value;
    const status = statusFilter.value;
    const searchTerm = productSearch.value.toLowerCase();
    fetch('/api/inventory-products').then(res => res.json()).then(data => {
        if (!data.success) throw new Error('获取数据失败');
        let filtered = data.data;
        if (category !== 'all') filtered = filtered.filter(item => item.category === category);
        if (status !== 'all') {
            switch(status) {
                case 'normal': filtered = filtered.filter(item => item.status === '正常'); break;
                case 'warning': filtered = filtered.filter(item => item.status === '预警'); break;
                case 'outofstock': filtered = filtered.filter(item => item.status === '缺货'); break;
            }
        }
        if (searchTerm) {
            filtered = filtered.filter(item =>
                (item.product_name && item.product_name.toLowerCase().includes(searchTerm)) ||
                (item.product_code && item.product_code.toLowerCase().includes(searchTerm))
            );
        }
        updateInventoryProductTable(filtered);
    }).catch(err => {
        const tableBody = document.getElementById('inventory-list');
        if (tableBody) {
            tableBody.innerHTML = `<tr><td colspan="7" class="error-message">搜索失败：${err.message}</td></tr>`;
        }
    });
}

function editInventoryAlertByProductCode(productCode) {
    // 直接弹窗设置/编辑预警阈值，无则新建
    fetch(`/api/inventory-alerts`).then(res => res.json()).then(data => {
        if (data.success) {
            const found = data.data.find(item => item.product_code === productCode);
            if (found) {
                editInventoryAlert(found.id);
            } else {
                // 没有则直接弹窗新建
                showAddAlertModalForProduct(productCode);
            }
        }
    });
}

function showAddAlertModalForProduct(productCode) {
    // 拉取商品信息
    fetch(`/api/products/${productCode}`).then(res => res.json()).then(data => {
        if (!data.success) {
            showNotification('获取商品信息失败', 'error');
            return;
        }
        const product = data.data;
        // 创建模态框
        moduleContent.innerHTML += `
            <div class="modal inventory-modal" id="add-alert-modal">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3>设置库存预警阈值</h3>
                        <span class="close-modal">&times;</span>
                    </div>
                    <div class="modal-body">
                        <form id="add-alert-form" class="inventory-form">
                            <div class="form-group">
                                <label>商品：</label>
                                <input type="text" class="form-control" value="${product.product_name} (${product.product_code})" readonly>
                            </div>
                            <div class="form-group">
                                <label for="min-stock">库存预警下限：</label>
                                <input type="number" id="min-stock" class="form-control" min="0" required>
                                <span class="form-hint">当库存低于此值时将发出预警</span>
                            </div>
                            <div class="form-actions">
                                <button type="button" class="btn-cancel">取消</button>
                                <button type="submit" class="btn-save">保存</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        `;
        // 显示模态框
        const modal = document.getElementById('add-alert-modal');
        modal.style.display = 'block';
        // 关闭模态框事件
        modal.querySelector('.close-modal').onclick = () => modal.remove();
        modal.querySelector('.btn-cancel').onclick = () => modal.remove();
        // 表单提交
        modal.querySelector('#add-alert-form').onsubmit = function(e) {
            e.preventDefault();
            const minStock = parseInt(document.getElementById('min-stock').value);
            if (isNaN(minStock) || minStock < 0) {
                showNotification('请输入有效的库存下限', 'error');
                return;
            }
            fetch('/api/inventory-alerts', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ product_code: productCode, min_stock: minStock })
            }).then(res => res.json()).then(data => {
                if (data.success) {
                    showNotification('预警阈值设置成功', 'success');
                    modal.remove();
                    loadInventoryManagement();
                } else {
                    showNotification(data.message || '设置失败', 'error');
                }
            }).catch(() => {
                showNotification('请求失败', 'error');
            });
        };
    });
}

// 加载商品信息录入模块
function loadProductInput() {
    // 获取分类和供应商数据
    Promise.all([
        fetch('/api/categories').then(res => res.json()),
        fetch('/api/suppliers').then(res => res.json())
    ])
    .then(([categoriesResponse, suppliersResponse]) => {
        if (!categoriesResponse.success || !suppliersResponse.success) {
            throw new Error('获取数据失败');
        }
        
        const categories = categoriesResponse.data;
        const suppliers = suppliersResponse.data;
        
        // 渲染商品信息录入表单
        moduleContent.innerHTML = `
            <div class="module-header">
                <h2>商品信息录入</h2>
            </div>
            
            <div class="product-form-container">
                <form id="product-form" class="product-form">
                    <div class="form-group">
                        <label for="product-code">商品编码</label>
                        <input type="text" id="product-code" class="form-control" placeholder="请输入商品编码或留空自动生成">
                    </div>
                    
                    <div class="form-group">
                        <label for="product-name">商品名称</label>
                        <input type="text" id="product-name" class="form-control" placeholder="请输入商品名称" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="product-category">商品分类</label>
                        <select id="product-category" class="form-control" required>
                            <option value="">请选择分类</option>
                            ${categories.map(cat => `<option value="${cat.name}">${cat.name}</option>`).join('')}
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="product-price">商品价格</label>
                        <input type="number" id="product-price" class="form-control" placeholder="请输入商品价格" min="0.01" step="0.01" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="initial-stock">初始库存</label>
                        <input type="number" id="initial-stock" class="form-control" placeholder="请输入初始库存" min="0" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="product-supplier">供应商</label>
                        <select id="product-supplier" class="form-control" required>
                            <option value="">请选择供应商</option>
                            ${suppliers.map(sup => `<option value="${sup.name}">${sup.name}</option>`).join('')}
                        </select>
                    </div>
                    
                    <div class="form-actions">
                        <button type="submit" class="btn-save">保存</button>
                        <button type="reset" class="btn-reset">重置</button>
                    </div>
                </form>
            </div>
            
            <div class="product-list-container">
                <h3>商品列表</h3>
                <div class="table-container">
                    <table class="product-table">
                        <thead>
                            <tr>
                                <th>商品编码</th>
                                <th>商品名称</th>
                                <th>分类</th>
                                <th>价格</th>
                                <th>初始库存</th>
                                <th>当前库存</th>
                                <th>供应商</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="product-list">
                            <tr>
                                <td colspan="8" class="loading">加载中...</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        `;
        
        // 加载商品列表
        loadProductList();
        
        // 添加表单提交事件处理
        document.getElementById('product-form').addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 获取表单数据
            const productData = {
                product_code: document.getElementById('product-code').value,
                product_name: document.getElementById('product-name').value,
                category: document.getElementById('product-category').value,
                price: document.getElementById('product-price').value,
                initial_stock: document.getElementById('initial-stock').value,
                supplier: document.getElementById('product-supplier').value
            };
            
            // 发送请求添加商品
            fetch('/api/products', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(productData)
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    showNotification('商品添加成功', 'success');
                    // 重置表单
                    document.getElementById('product-form').reset();
                    // 重新加载商品列表
                    loadProductList();
                } else {
                    showNotification('商品添加失败：' + data.message, 'error');
                }
            })
            .catch(err => {
                console.error('添加商品请求失败:', err);
                showNotification('添加商品请求失败，请检查网络连接', 'error');
            });
        });
    })
    .catch(err => {
        console.error('加载商品信息录入模块失败:', err);
        moduleContent.innerHTML = `
            <div class="error-message">
                加载商品信息录入模块失败：${err.message}
            </div>
        `;
    });
}

// 加载商品列表
function loadProductList() {
    const productListElement = document.getElementById('product-list');
    if (!productListElement) return;
    
    productListElement.innerHTML = '<tr><td colspan="8" class="loading">加载中...</td></tr>';
    
    fetch('/api/products')
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            if (data.data.length === 0) {
                productListElement.innerHTML = '<tr><td colspan="8" class="no-data">暂无商品数据</td></tr>';
                return;
            }
            
            productListElement.innerHTML = '';
            data.data.forEach(product => {
                productListElement.innerHTML += `
                    <tr data-id="${product.id}">
                        <td>${product.product_code}</td>
                        <td>${product.product_name}</td>
                        <td>${product.category}</td>
                        <td>¥${parseFloat(product.price).toFixed(2)}</td>
                        <td>${product.initial_stock}</td>
                        <td>${product.current_stock}</td>
                        <td>${product.supplier}</td>
                        <td>
                            <button class="btn-edit-product" data-code="${product.product_code}">编辑</button>
                            <button class="btn-delete-product" data-code="${product.product_code}">删除</button>
                        </td>
                    </tr>
                `;
            });
            
            // 添加编辑和删除按钮事件处理
            document.querySelectorAll('.btn-edit-product').forEach(btn => {
                btn.addEventListener('click', function() {
                    const productCode = this.getAttribute('data-code');
                    editProduct(productCode);
                });
            });
            
            document.querySelectorAll('.btn-delete-product').forEach(btn => {
                btn.addEventListener('click', function() {
                    const productCode = this.getAttribute('data-code');
                    if (confirm('确定要删除此商品吗？')) {
                        deleteProduct(productCode);
                    }
                });
            });
        } else {
            productListElement.innerHTML = `<tr><td colspan="8" class="error-message">加载失败：${data.message}</td></tr>`;
        }
    })
    .catch(err => {
        console.error('加载商品列表失败:', err);
        productListElement.innerHTML = `<tr><td colspan="8" class="error-message">加载失败：${err.message}</td></tr>`;
    });
}

// 编辑商品
function editProduct(productCode) {
    fetch(`/api/products/${productCode}`)
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            const product = data.data;
            
            // 打开编辑弹窗
            moduleContent.innerHTML += `
                <div class="modal" id="edit-product-modal">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h3>编辑商品信息</h3>
                            <span class="close-modal">&times;</span>
                        </div>
                        <div class="modal-body">
                            <form id="edit-product-form" class="product-form">
                                <div class="form-group">
                                    <label for="edit-product-code">商品编码</label>
                                    <input type="text" id="edit-product-code" class="form-control" value="${product.product_code}" readonly>
                                </div>
                                
                                <div class="form-group">
                                    <label for="edit-product-name">商品名称</label>
                                    <input type="text" id="edit-product-name" class="form-control" value="${product.product_name}" required>
                                </div>
                                
                                <div class="form-group">
                                    <label for="edit-product-category">商品分类</label>
                                    <select id="edit-product-category" class="form-control" required>
                                        <!-- 分类选项将通过JS动态添加 -->
                                    </select>
                                </div>
                                
                                <div class="form-group">
                                    <label for="edit-product-price">商品价格</label>
                                    <input type="number" id="edit-product-price" class="form-control" value="${product.price}" min="0.01" step="0.01" required>
                                </div>
                                
                                <div class="form-group">
                                    <label for="edit-initial-stock">初始库存</label>
                                    <input type="number" id="edit-initial-stock" class="form-control" value="${product.initial_stock}" min="0" required>
                                </div>
                                
                                <div class="form-group">
                                    <label for="edit-product-supplier">供应商</label>
                                    <select id="edit-product-supplier" class="form-control" required>
                                        <!-- 供应商选项将通过JS动态添加 -->
                                    </select>
                                </div>
                                
                                <div class="form-actions">
                                    <button type="submit" class="btn-save">保存修改</button>
                                    <button type="button" class="btn-cancel">取消</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            `;
            
            // 获取分类和供应商数据并填充下拉框
            Promise.all([
                fetch('/api/categories').then(res => res.json()),
                fetch('/api/suppliers').then(res => res.json())
            ])
            .then(([categoriesResponse, suppliersResponse]) => {
                const categorySelect = document.getElementById('edit-product-category');
                const supplierSelect = document.getElementById('edit-product-supplier');
                
                // 填充分类选项
                categoriesResponse.data.forEach(cat => {
                    const option = document.createElement('option');
                    option.value = cat.name;
                    option.textContent = cat.name;
                    if (cat.name === product.category) {
                        option.selected = true;
                    }
                    categorySelect.appendChild(option);
                });
                
                // 填充供应商选项
                suppliersResponse.data.forEach(sup => {
                    const option = document.createElement('option');
                    option.value = sup.name;
                    option.textContent = sup.name;
                    if (sup.name === product.supplier) {
                        option.selected = true;
                    }
                    supplierSelect.appendChild(option);
                });
            });
            
            // 显示弹窗
            const modal = document.getElementById('edit-product-modal');
            modal.style.display = 'block';
            
            // 关闭弹窗事件
            document.querySelector('.close-modal').addEventListener('click', function() {
                modal.remove();
            });
            
            document.querySelector('.btn-cancel').addEventListener('click', function() {
                modal.remove();
            });
            
            // 表单提交事件
            document.getElementById('edit-product-form').addEventListener('submit', function(e) {
                e.preventDefault();
                
                // 获取修改后的数据
                const updatedData = {
                    product_name: document.getElementById('edit-product-name').value,
                    category: document.getElementById('edit-product-category').value,
                    price: document.getElementById('edit-product-price').value,
                    initial_stock: document.getElementById('edit-initial-stock').value,
                    supplier: document.getElementById('edit-product-supplier').value
                };
                
                // 发送请求更新商品
                fetch(`/api/products/${productCode}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(updatedData)
                })
                .then(res => res.json())
                .then(data => {
                    if (data.success) {
                        alert('商品更新成功');
                        modal.remove();
                        // 重新加载商品列表
                        loadProductList();
                    } else {
                        alert('商品更新失败：' + data.message);
                    }
                })
                .catch(err => {
                    console.error('更新商品请求失败:', err);
                    alert('更新商品请求失败，请检查网络连接');
                });
            });
        } else {
            alert('获取商品信息失败：' + data.message);
        }
    })
    .catch(err => {
        console.error('获取商品信息失败:', err);
        alert('获取商品信息失败，请检查网络连接');
    });
}

// 删除商品
function deleteProduct(productCode) {
    fetch(`/api/products/${productCode}`, {
        method: 'DELETE'
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            alert('商品删除成功');
            // 重新加载商品列表
            loadProductList();
        } else {
            alert('商品删除失败：' + data.message);
        }
    })
    .catch(err => {
        console.error('删除商品请求失败:', err);
        alert('删除商品请求失败，请检查网络连接');
    });
}

// 加载促销活动管理模块
function loadPromotionManagement() {
    // 获取分类数据
    fetch('/api/categories')
    .then(res => res.json())
    .then(categoriesResponse => {
        if (!categoriesResponse.success) {
            throw new Error('获取分类数据失败');
        }
        
        const categories = categoriesResponse.data;
        
        // 渲染促销活动管理界面
        moduleContent.innerHTML = `
            <div class="module-header">
                <h2>创建新促销</h2>
            </div>
            
            <div class="promotion-form-container">
                <form id="promotion-form" class="promotion-form">
                    <div class="form-group">
                        <label for="promotion-name">活动名称</label>
                        <input type="text" id="promotion-name" class="form-control" placeholder="例如: 限时折扣等" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="promotion-discount">折扣力度</label>
                        <input type="number" id="promotion-discount" class="form-control" placeholder="0.0" min="0" step="0.01" required>
                    </div>
                    
                    <div class="form-group">
                        <label>时间范围</label>
                        <div class="date-time-group">
                            <input type="text" id="start-date" class="form-control" placeholder="开始日期" onfocus="(this.type='date')" required>
                            <input type="text" id="start-time" class="form-control" placeholder="开始时间" onfocus="(this.type='time')" required>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label>至</label>
                        <div class="date-time-group">
                            <input type="text" id="end-date" class="form-control" placeholder="结束日期" onfocus="(this.type='date')" required>
                            <input type="text" id="end-time" class="form-control" placeholder="结束时间" onfocus="(this.type='time')" required>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="promotion-category">适用分类</label>
                        <select id="promotion-category" class="form-control" required>
                            <option value="">请选择分类</option>
                            ${categories.map(cat => `<option value="${cat.name}">${cat.name}</option>`).join('')}
                            <option value="全部分类">全部分类</option>
                        </select>
                    </div>
                    
                    <div class="form-group promotion-description">
                        <label for="promotion-description">活动描述</label>
                        <textarea id="promotion-description" placeholder="请输入促销规则和详细说明"></textarea>
                    </div>
                    
                    <div class="form-actions">
                        <button type="submit" class="btn-save">立即创建</button>
                        <button type="reset" class="btn-reset">重置</button>
                    </div>
                </form>
            </div>
            
            <div class="module-header">
                <h2>活动列表</h2>
            </div>
            
            <div class="product-list-container">
                <div class="table-container">
                    <table class="promotion-table">
                        <thead>
                            <tr>
                                <th>活动名称</th>
                                <th>折扣</th>
                                <th>状态</th>
                                <th>时间范围</th>
                                <th>适用分类</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="promotion-list">
                            <tr>
                                <td colspan="6" class="loading">加载中...</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        `;
        
        // 初始化日期选择器的默认值
        const today = new Date();
        const nextMonth = new Date();
        nextMonth.setMonth(today.getMonth() + 1);
        
        document.getElementById('start-date').value = formatDate(today);
        document.getElementById('end-date').value = formatDate(nextMonth);
        document.getElementById('start-time').value = '00:00';
        document.getElementById('end-time').value = '23:59';
        
        // 加载促销活动列表
        loadPromotionList();
        
        // 添加表单提交事件处理
        document.getElementById('promotion-form').addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 获取表单数据
            const promotionData = {
                name: document.getElementById('promotion-name').value,
                discount: document.getElementById('promotion-discount').value,
                start_date: document.getElementById('start-date').value.replace(/-/g, '/'),
                start_time: document.getElementById('start-time').value,
                end_date: document.getElementById('end-date').value.replace(/-/g, '/'),
                end_time: document.getElementById('end-time').value,
                category: document.getElementById('promotion-category').value,
                description: document.getElementById('promotion-description').value
            };
            
            // 发送请求添加促销活动
            fetch('/api/promotions', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(promotionData)
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    alert('促销活动创建成功');
                    // 重置表单
                    document.getElementById('promotion-form').reset();
                    // 设置默认日期和时间
                    document.getElementById('start-date').value = formatDate(today);
                    document.getElementById('end-date').value = formatDate(nextMonth);
                    document.getElementById('start-time').value = '00:00';
                    document.getElementById('end-time').value = '23:59';
                    // 重新加载促销活动列表
                    loadPromotionList();
                } else {
                    alert('促销活动创建失败：' + data.message);
                }
            })
            .catch(err => {
                console.error('创建促销活动请求失败:', err);
                alert('创建促销活动请求失败，请检查网络连接');
            });
        });
    })
    .catch(err => {
        console.error('加载促销活动管理模块失败:', err);
        moduleContent.innerHTML = `
            <div class="error-message">
                加载促销活动管理模块失败：${err.message}
            </div>
        `;
    });
}

// 加载促销活动列表
function loadPromotionList() {
    const promotionListElement = document.getElementById('promotion-list');
    if (!promotionListElement) return;
    
    promotionListElement.innerHTML = '<tr><td colspan="6" class="loading">加载中...</td></tr>';
    
    fetch('/api/promotions')
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            if (data.data.length === 0) {
                promotionListElement.innerHTML = '<tr><td colspan="6" class="no-data">暂无促销活动数据</td></tr>';
                return;
            }
            
            promotionListElement.innerHTML = '';
            data.data.forEach(promotion => {
                // 根据状态设置不同的样式类
                let statusClass = '';
                if (promotion.status === '进行中') {
                    statusClass = 'status-ongoing';
                } else if (promotion.status === '未开始') {
                    statusClass = 'status-pending';
                } else {
                    statusClass = 'status-ended';
                }
                
                promotionListElement.innerHTML += `
                    <tr data-id="${promotion.id}">
                        <td>${promotion.name}</td>
                        <td>${promotion.discount}</td>
                        <td><span class="status-tag ${statusClass}">${promotion.status}</span></td>
                        <td>${promotion.start_date} ${promotion.start_time} 至 ${promotion.end_date} ${promotion.end_time}</td>
                        <td>${promotion.category}</td>
                        <td>
                            <button class="btn-edit-promotion" data-id="${promotion.id}">编辑</button>
                            <button class="btn-delete-promotion" data-id="${promotion.id}">删除</button>
                        </td>
                    </tr>
                `;
            });
            
            // 添加编辑和删除按钮事件处理
            document.querySelectorAll('.btn-edit-promotion').forEach(btn => {
                btn.addEventListener('click', function() {
                    const promotionId = this.getAttribute('data-id');
                    editPromotion(promotionId);
                });
            });
            
            document.querySelectorAll('.btn-delete-promotion').forEach(btn => {
                btn.addEventListener('click', function() {
                    const promotionId = this.getAttribute('data-id');
                    if (confirm('确定要删除此促销活动吗？')) {
                        deletePromotion(promotionId);
                    }
                });
            });
        } else {
            promotionListElement.innerHTML = `<tr><td colspan="6" class="error-message">加载失败：${data.message}</td></tr>`;
        }
    })
    .catch(err => {
        console.error('加载促销活动列表失败:', err);
        promotionListElement.innerHTML = `<tr><td colspan="6" class="error-message">加载失败：${err.message}</td></tr>`;
    });
}

// 编辑促销活动
function editPromotion(promotionId) {
    Promise.all([
        fetch(`/api/promotions/${promotionId}`).then(res => res.json()),
        fetch('/api/categories').then(res => res.json())
    ])
    .then(([promotionResponse, categoriesResponse]) => {
        if (!promotionResponse.success || !categoriesResponse.success) {
            throw new Error('获取数据失败');
        }
        
        const promotion = promotionResponse.data;
        const categories = categoriesResponse.data;
        
        // 打开编辑弹窗
        moduleContent.innerHTML += `
            <div class="modal" id="edit-promotion-modal">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3>编辑促销活动</h3>
                        <span class="close-modal">&times;</span>
                    </div>
                    <div class="modal-body">
                        <form id="edit-promotion-form" class="promotion-form">
                            <div class="form-group">
                                <label for="edit-promotion-name">活动名称</label>
                                <input type="text" id="edit-promotion-name" class="form-control" value="${promotion.name}" required>
                            </div>
                            
                            <div class="form-group">
                                <label for="edit-promotion-discount">折扣力度</label>
                                <input type="number" id="edit-promotion-discount" class="form-control" value="${promotion.discount}" min="0" step="0.1" required>
                            </div>
                            
                            <div class="form-group">
                                <label>时间范围</label>
                                <div class="date-time-group">
                                    <input type="date" id="edit-start-date" class="form-control" value="${formatDateForInput(promotion.start_date)}" required>
                                    <input type="time" id="edit-start-time" class="form-control" value="${promotion.start_time}" required>
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <label>至</label>
                                <div class="date-time-group">
                                    <input type="date" id="edit-end-date" class="form-control" value="${formatDateForInput(promotion.end_date)}" required>
                                    <input type="time" id="edit-end-time" class="form-control" value="${promotion.end_time}" required>
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <label for="edit-promotion-category">适用分类</label>
                                <select id="edit-promotion-category" class="form-control" required>
                                    <option value="">请选择分类</option>
                                    ${categories.map(cat => `<option value="${cat.name}" ${cat.name === promotion.category ? 'selected' : ''}>${cat.name}</option>`).join('')}
                                    <option value="全部分类" ${promotion.category === '全部分类' ? 'selected' : ''}>全部分类</option>
                                </select>
                            </div>
                            
                            <div class="form-group promotion-description">
                                <label for="edit-promotion-description">活动描述</label>
                                <textarea id="edit-promotion-description">${promotion.description || ''}</textarea>
                            </div>
                            
                            <div class="form-actions">
                                <button type="submit" class="btn-save">保存修改</button>
                                <button type="button" class="btn-cancel">取消</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        `;
        
        // 显示弹窗
        const modal = document.getElementById('edit-promotion-modal');
        modal.style.display = 'block';
        
        // 关闭弹窗事件
        document.querySelector('.close-modal').addEventListener('click', function() {
            modal.remove();
        });
        
        document.querySelector('.btn-cancel').addEventListener('click', function() {
            modal.remove();
        });
        
        // 表单提交事件
        document.getElementById('edit-promotion-form').addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 获取修改后的数据
            const updatedData = {
                name: document.getElementById('edit-promotion-name').value,
                discount: document.getElementById('edit-promotion-discount').value,
                start_date: document.getElementById('edit-start-date').value.replace(/-/g, '/'),
                start_time: document.getElementById('edit-start-time').value,
                end_date: document.getElementById('edit-end-date').value.replace(/-/g, '/'),
                end_time: document.getElementById('edit-end-time').value,
                category: document.getElementById('edit-promotion-category').value,
                description: document.getElementById('edit-promotion-description').value
            };
            
            // 发送请求更新促销活动
            fetch(`/api/promotions/${promotionId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(updatedData)
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    alert('促销活动更新成功');
                    modal.remove();
                    // 重新加载促销活动列表
                    loadPromotionList();
                } else {
                    alert('促销活动更新失败：' + data.message);
                }
            })
            .catch(err => {
                console.error('更新促销活动请求失败:', err);
                alert('更新促销活动请求失败，请检查网络连接');
            });
        });
    })
    .catch(err => {
        console.error('获取促销活动信息失败:', err);
        alert('获取促销活动信息失败，请检查网络连接');
    });
}

// 删除促销活动
function deletePromotion(promotionId) {
    fetch(`/api/promotions/${promotionId}`, {
        method: 'DELETE'
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            alert('促销活动删除成功');
            // 重新加载促销活动列表
            loadPromotionList();
        } else {
            alert('促销活动删除失败：' + data.message);
        }
    })
    .catch(err => {
        console.error('删除促销活动请求失败:', err);
        alert('删除促销活动请求失败，请检查网络连接');
    });
}

// 日期格式化函数，将Date对象转换为YYYY-MM-DD格式
function formatDate(date) {
    // 如果date是字符串，则直接返回
    if (typeof date === 'string') {
        return date;
    }
    
    // 否则按照Date对象处理
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}

// 将 'YYYY/MM/DD' 格式的日期转换为 'YYYY-MM-DD' 格式，用于date输入框
function formatDateForInput(dateStr) {
    if (!dateStr) return '';
    
    // 如果是Date对象，转换为YYYY-MM-DD格式
    if (dateStr instanceof Date) {
        const year = dateStr.getFullYear();
        const month = String(dateStr.getMonth() + 1).padStart(2, '0');
        const day = String(dateStr.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    }
    
    // 如果是字符串，替换/为-
    if (typeof dateStr === 'string') {
        return dateStr.replace(/\//g, '-');
    }
    
    // 如果不是以上类型，返回空字符串
    return '';
}

// 加载分类管理模块
function loadCategoryManagement() {
    moduleContent.innerHTML = `
        <div class="module-header">
            <h2>商品分类管理</h2>
        </div>
        
        <div class="product-form-container">
            <form id="category-form" class="product-form">
                <div class="form-group">
                    <label for="category-name">分类名称</label>
                    <input type="text" id="category-name" class="form-control" placeholder="请输入分类名称" required>
                </div>
                
                <div class="form-group">
                    <label for="category-description">分类描述</label>
                    <textarea id="category-description" class="form-control" placeholder="请输入分类描述"></textarea>
                </div>
                
                <div class="form-actions">
                    <button type="submit" class="btn-save">添加分类</button>
                    <button type="reset" class="btn-reset">重置</button>
                </div>
            </form>
        </div>
        
        <div class="product-list-container">
            <h3>分类列表</h3>
            <div class="table-container">
                <table class="product-table">
                    <thead>
                        <tr>
                            <th>分类名称</th>
                            <th>描述</th>
                            <th>创建时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="category-list">
                        <tr>
                            <td colspan="4" class="loading">加载中...</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    `;
    
    // 加载分类列表
    loadCategoryList();
    
    // 添加表单提交事件处理
    document.getElementById('category-form').addEventListener('submit', function(e) {
        e.preventDefault();
        
        // 获取表单数据
        const categoryData = {
            name: document.getElementById('category-name').value,
            description: document.getElementById('category-description').value
        };
        
        // 发送请求添加分类
        fetch('/api/categories', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(categoryData)
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                alert('分类添加成功');
                // 重置表单
                document.getElementById('category-form').reset();
                // 重新加载分类列表
                loadCategoryList();
            } else {
                alert('分类添加失败：' + data.message);
            }
        })
        .catch(err => {
            console.error('添加分类请求失败:', err);
            alert('添加分类请求失败，请检查网络连接');
        });
    });
}

// 加载分类列表
function loadCategoryList() {
    const categoryListElement = document.getElementById('category-list');
    if (!categoryListElement) return;
    
    categoryListElement.innerHTML = '<tr><td colspan="4" class="loading">加载中...</td></tr>';
    
    fetch('/api/categories')
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            if (data.data.length === 0) {
                categoryListElement.innerHTML = '<tr><td colspan="4" class="no-data">暂无分类数据</td></tr>';
                return;
            }
            
            categoryListElement.innerHTML = '';
            data.data.forEach(category => {
                categoryListElement.innerHTML += `
                    <tr data-id="${category.id}">
                        <td>${category.name}</td>
                        <td>${category.description || '无'}</td>
                        <td>${category.create_time}</td>
                        <td>
                            <button class="btn-edit-category" data-id="${category.id}">编辑</button>
                            <button class="btn-delete-category" data-id="${category.id}">删除</button>
                        </td>
                    </tr>
                `;
            });
            
            // 添加编辑和删除按钮事件处理
            document.querySelectorAll('.btn-edit-category').forEach(btn => {
                btn.addEventListener('click', function() {
                    const categoryId = this.getAttribute('data-id');
                    editCategory(categoryId);
                });
            });
            
            document.querySelectorAll('.btn-delete-category').forEach(btn => {
                btn.addEventListener('click', function() {
                    const categoryId = this.getAttribute('data-id');
                    if (confirm('确定要删除此分类吗？删除分类可能会影响相关商品。')) {
                        deleteCategory(categoryId);
                    }
                });
            });
        } else {
            categoryListElement.innerHTML = `<tr><td colspan="4" class="error-message">加载失败：${data.message}</td></tr>`;
        }
    })
    .catch(err => {
        console.error('加载分类列表失败:', err);
        categoryListElement.innerHTML = `<tr><td colspan="4" class="error-message">加载失败：${err.message}</td></tr>`;
    });
}

// 编辑分类
function editCategory(categoryId) {
    fetch(`/api/categories/${categoryId}`)
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            const category = data.data;
            
            // 打开编辑弹窗
            moduleContent.innerHTML += `
                <div class="modal" id="edit-category-modal">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h3>编辑分类信息</h3>
                            <span class="close-modal">&times;</span>
                        </div>
                        <div class="modal-body">
                            <form id="edit-category-form" class="product-form">
                                <div class="form-group">
                                    <label for="edit-category-name">分类名称</label>
                                    <input type="text" id="edit-category-name" class="form-control" value="${category.name}" required>
                                </div>
                                
                                <div class="form-group">
                                    <label for="edit-category-description">分类描述</label>
                                    <textarea id="edit-category-description" class="form-control">${category.description || ''}</textarea>
                                </div>
                                
                                <div class="form-actions">
                                    <button type="submit" class="btn-save">保存修改</button>
                                    <button type="button" class="btn-cancel">取消</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            `;
            
            // 显示弹窗
            const modal = document.getElementById('edit-category-modal');
            modal.style.display = 'block';
            
            // 关闭弹窗事件
            document.querySelector('.close-modal').addEventListener('click', function() {
                modal.remove();
            });
            
            document.querySelector('.btn-cancel').addEventListener('click', function() {
                modal.remove();
            });
            
            // 表单提交事件
            document.getElementById('edit-category-form').addEventListener('submit', function(e) {
                e.preventDefault();
                
                // 获取修改后的数据
                const updatedData = {
                    name: document.getElementById('edit-category-name').value,
                    description: document.getElementById('edit-category-description').value
                };
                
                // 发送请求更新分类
                fetch(`/api/categories/${categoryId}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(updatedData)
                })
                .then(res => res.json())
                .then(data => {
                    if (data.success) {
                        alert('分类更新成功');
                        modal.remove();
                        // 重新加载分类列表
                        loadCategoryList();
                    } else {
                        alert('分类更新失败：' + data.message);
                    }
                })
                .catch(err => {
                    console.error('更新分类请求失败:', err);
                    alert('更新分类请求失败，请检查网络连接');
                });
            });
        } else {
            alert('获取分类信息失败：' + data.message);
        }
    })
    .catch(err => {
        console.error('获取分类信息失败:', err);
        alert('获取分类信息失败，请检查网络连接');
    });
}

// 删除分类
function deleteCategory(categoryId) {
    fetch(`/api/categories/${categoryId}`, {
        method: 'DELETE'
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            alert('分类删除成功');
            // 重新加载分类列表
            loadCategoryList();
        } else {
            alert('分类删除失败：' + data.message);
        }
    })
    .catch(err => {
        console.error('删除分类请求失败:', err);
        alert('删除分类请求失败，请检查网络连接');
    });
}

// 加载商品价格管理模块
function loadPriceManagement() {
    // 获取商品数据
    fetch('/api/products')
    .then(res => res.json())
    .then(productsResponse => {
        if (!productsResponse.success) {
            throw new Error('获取商品数据失败');
        }
        
        const products = productsResponse.data;
        
        // 渲染商品价格管理界面
        moduleContent.innerHTML = `
            <div class="module-header">
                <h2>商品价格管理</h2>
            </div>
            
            <div class="product-form-container">
                <form id="price-adjustment-form" class="product-form">
                    <div class="form-group">
                        <label for="product-select">选择商品</label>
                        <select id="product-select" class="form-control" required>
                            <option value="">请选择商品</option>
                            ${products.map(product => `<option value="${product.product_code}" data-price="${product.price}">${product.product_name} (当前价格: ¥${parseFloat(product.price).toFixed(2)})</option>`).join('')}
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="current-price">当前价格</label>
                        <input type="text" id="current-price" class="form-control" readonly>
                    </div>
                    
                    <div class="form-group">
                        <label for="new-price">新价格</label>
                        <input type="number" id="new-price" class="form-control" placeholder="请输入新价格" min="0.01" step="0.01" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="price-operator">操作人</label>
                        <input type="text" id="price-operator" class="form-control" placeholder="请输入操作人姓名" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="price-reason">调整原因</label>
                        <textarea id="price-reason" class="form-control" placeholder="请输入价格调整原因" required></textarea>
                    </div>
                    
                    <div class="form-actions">
                        <button type="submit" class="btn-save">提交调整</button>
                        <button type="reset" class="btn-reset">重置</button>
                    </div>
                </form>
            </div>
            
            <div class="module-header">
                <h2>价格调整历史</h2>
            </div>
            
            <div class="product-list-container">
                <div class="table-container">
                    <table class="product-table">
                        <thead>
                            <tr>
                                <th>商品编码</th>
                                <th>商品名称</th>
                                <th>原价格</th>
                                <th>新价格</th>
                                <th>调整日期</th>
                                <th>操作人</th>
                                <th>调整原因</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="price-adjustment-list">
                            <tr>
                                <td colspan="8" class="loading">加载中...</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        `;
        
        // 加载价格调整记录
        loadPriceAdjustmentList();
        
        // 添加商品选择事件，更新当前价格
        document.getElementById('product-select').addEventListener('change', function() {
            const selectedOption = this.options[this.selectedIndex];
            const currentPrice = selectedOption.getAttribute('data-price');
            document.getElementById('current-price').value = currentPrice ? `¥${parseFloat(currentPrice).toFixed(2)}` : '';
            
            // 重置新价格
            document.getElementById('new-price').value = '';
        });
        
        // 添加表单提交事件处理
        document.getElementById('price-adjustment-form').addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 获取表单数据
            const productSelect = document.getElementById('product-select');
            const productCode = productSelect.value;
            
            if (!productCode) {
                alert('请选择商品');
                return;
            }
            
            const adjustmentData = {
                product_code: productCode,
                new_price: document.getElementById('new-price').value,
                operator: document.getElementById('price-operator').value,
                reason: document.getElementById('price-reason').value
            };
            
            // 发送请求添加价格调整记录
            fetch('/api/price-adjustments', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(adjustmentData)
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    alert('价格调整成功');
                    
                    // 更新选择框中的价格显示
                    const selectedOption = productSelect.options[productSelect.selectedIndex];
                    selectedOption.setAttribute('data-price', adjustmentData.new_price);
                    selectedOption.textContent = `${selectedOption.textContent.split('(')[0]} (当前价格: ¥${parseFloat(adjustmentData.new_price).toFixed(2)})`;
                    
                    // 更新当前价格显示
                    document.getElementById('current-price').value = `¥${parseFloat(adjustmentData.new_price).toFixed(2)}`;
                    
                    // 重置表单
                    document.getElementById('new-price').value = '';
                    document.getElementById('price-reason').value = '';
                    
                    // 重新加载价格调整记录
                    loadPriceAdjustmentList();
                } else {
                    alert('价格调整失败：' + data.message);
                }
            })
            .catch(err => {
                console.error('价格调整请求失败:', err);
                alert('价格调整请求失败，请检查网络连接');
            });
        });
    })
    .catch(err => {
        console.error('加载商品价格管理模块失败:', err);
        moduleContent.innerHTML = `
            <div class="error-message">
                加载商品价格管理模块失败：${err.message}
            </div>
        `;
    });
}

// 加载价格调整记录列表
function loadPriceAdjustmentList() {
    const priceAdjustmentListElement = document.getElementById('price-adjustment-list');
    if (!priceAdjustmentListElement) return;
    
    priceAdjustmentListElement.innerHTML = '<tr><td colspan="8" class="loading">加载中...</td></tr>';
    
    fetch('/api/price-adjustments')
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            if (data.data.length === 0) {
                priceAdjustmentListElement.innerHTML = '<tr><td colspan="8" class="no-data">暂无价格调整记录</td></tr>';
                return;
            }
            
            priceAdjustmentListElement.innerHTML = '';
            data.data.forEach(adjustment => {
                // 计算价格变化百分比
                const oldPrice = parseFloat(adjustment.old_price);
                const newPrice = parseFloat(adjustment.new_price);
                const priceDiff = newPrice - oldPrice;
                const priceChangePercent = (priceDiff / oldPrice * 100).toFixed(2);
                
                // 设置价格变化的显示样式
                const priceChangeClass = priceDiff > 0 ? 'price-change-positive' : (priceDiff < 0 ? 'price-change-negative' : '');
                const priceChangeSign = priceDiff > 0 ? '+' : '';
                
                priceAdjustmentListElement.innerHTML += `
                    <tr data-id="${adjustment.id}">
                        <td>${adjustment.product_code}</td>
                        <td>${adjustment.product_name}</td>
                        <td>¥${parseFloat(adjustment.old_price).toFixed(2)}</td>
                        <td>
                            ¥${parseFloat(adjustment.new_price).toFixed(2)}
                            <span class="${priceChangeClass}">
                                (${priceChangeSign}${priceChangePercent}%)
                            </span>
                        </td>
                        <td>${adjustment.adjustment_date}</td>
                        <td>${adjustment.operator}</td>
                        <td>${adjustment.reason}</td>
                        <td>
                            <button class="btn-delete-price-adjustment" data-id="${adjustment.id}">删除</button>
                        </td>
                    </tr>
                `;
            });
            
            // 添加删除按钮事件处理
            document.querySelectorAll('.btn-delete-price-adjustment').forEach(btn => {
                btn.addEventListener('click', function() {
                    const adjustmentId = this.getAttribute('data-id');
                    if (confirm('确定要删除此价格调整记录吗？这不会影响商品的当前价格。')) {
                        deletePriceAdjustment(adjustmentId);
                    }
                });
            });
        } else {
            priceAdjustmentListElement.innerHTML = `<tr><td colspan="8" class="error-message">加载失败：${data.message}</td></tr>`;
        }
    })
    .catch(err => {
        console.error('加载价格调整记录失败:', err);
        priceAdjustmentListElement.innerHTML = `<tr><td colspan="8" class="error-message">加载失败：${err.message}</td></tr>`;
    });
}

// 删除价格调整记录
function deletePriceAdjustment(adjustmentId) {
    fetch(`/api/price-adjustments/${adjustmentId}`, {
        method: 'DELETE'
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            alert('价格调整记录删除成功');
            // 重新加载价格调整记录
            loadPriceAdjustmentList();
        } else {
            alert('价格调整记录删除失败：' + data.message);
        }
    })
    .catch(err => {
        console.error('删除价格调整记录请求失败:', err);
        alert('删除价格调整记录请求失败，请检查网络连接');
    });
}

// 加载仓库信息管理模块
function loadWarehouseManagement() {
    moduleContent.innerHTML = `
        <div class="module-header">
            <h2>仓库信息管理</h2>
        </div>
        
        <div class="product-form-container">
            <form id="warehouse-form" class="product-form">
                <div class="form-group">
                    <label for="warehouse-code">仓库编码</label>
                    <input type="text" id="warehouse-code" class="form-control" placeholder="例如: WH001" required>
                </div>
                
                <div class="form-group">
                    <label for="warehouse-name">仓库名称</label>
                    <input type="text" id="warehouse-name" class="form-control" placeholder="例如: 主仓库" required>
                </div>
                
                <div class="form-group">
                    <label for="warehouse-location">仓库位置</label>
                    <input type="text" id="warehouse-location" class="form-control" placeholder="例如: 北京市朝阳区" required>
                </div>
                
                <div class="form-group">
                    <label for="warehouse-area">仓库面积(平方米)</label>
                    <input type="number" id="warehouse-area" class="form-control" placeholder="例如: 5000" min="1" step="0.01" required>
                </div>
                
                <div class="form-group">
                    <label for="warehouse-manager">仓库管理员</label>
                    <input type="text" id="warehouse-manager" class="form-control" placeholder="例如: 李明" required>
                </div>
                
                <div class="form-group">
                    <label for="warehouse-contact">联系电话</label>
                    <input type="text" id="warehouse-contact" class="form-control" placeholder="例如: 13800138000">
                </div>
                
                <div class="form-group">
                    <label for="warehouse-status">仓库状态</label>
                    <select id="warehouse-status" class="form-control" required>
                        <option value="">请选择状态</option>
                        <option value="正常">正常</option>
                        <option value="维护中">维护中</option>
                        <option value="已关闭">已关闭</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="warehouse-description">仓库描述</label>
                    <textarea id="warehouse-description" class="form-control" placeholder="请输入仓库描述信息"></textarea>
                </div>
                
                <div class="form-actions">
                    <button type="submit" class="btn-save">添加仓库</button>
                    <button type="reset" class="btn-reset">重置</button>
                </div>
            </form>
        </div>
        
        <div class="module-header">
            <h2>仓库列表</h2>
        </div>
        
        <div class="product-list-container">
            <div class="table-container">
                <table class="warehouse-table">
                    <thead>
                        <tr>
                            <th>仓库编码</th>
                            <th>仓库名称</th>
                            <th>位置</th>
                            <th>面积(㎡)</th>
                            <th>管理员</th>
                            <th>联系电话</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="warehouse-list">
                        <tr>
                            <td colspan="8" class="loading">加载中...</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    `;
    
    // 加载仓库列表
    loadWarehouseList();
    
    // 添加表单提交事件处理
    document.getElementById('warehouse-form').addEventListener('submit', function(e) {
        e.preventDefault();
        
        // 获取表单数据
        const warehouseData = {
            warehouse_code: document.getElementById('warehouse-code').value,
            warehouse_name: document.getElementById('warehouse-name').value,
            location: document.getElementById('warehouse-location').value,
            area: document.getElementById('warehouse-area').value,
            manager: document.getElementById('warehouse-manager').value,
            contact_phone: document.getElementById('warehouse-contact').value,
            status: document.getElementById('warehouse-status').value,
            description: document.getElementById('warehouse-description').value
        };
        
        // 发送请求添加仓库
        fetch('/api/warehouses', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(warehouseData)
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                alert('仓库添加成功');
                // 重置表单
                document.getElementById('warehouse-form').reset();
                // 重新加载仓库列表
                loadWarehouseList();
            } else {
                alert('仓库添加失败：' + data.message);
            }
        })
        .catch(err => {
            console.error('添加仓库请求失败:', err);
            alert('添加仓库请求失败，请检查网络连接');
        });
    });
}

// 加载仓库列表
function loadWarehouseList() {
    const warehouseListElement = document.getElementById('warehouse-list');
    if (!warehouseListElement) return;
    
    warehouseListElement.innerHTML = '<tr><td colspan="8" class="loading">加载中...</td></tr>';
    
    fetch('/api/warehouses')
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            if (data.data.length === 0) {
                warehouseListElement.innerHTML = '<tr><td colspan="8" class="no-data">暂无仓库数据</td></tr>';
                return;
            }
            
            warehouseListElement.innerHTML = '';
            data.data.forEach(warehouse => {
                // 为不同状态设置不同的样式类
                let statusClass = '';
                if (warehouse.status === '正常') {
                    statusClass = 'status-normal';
                } else if (warehouse.status === '维护中') {
                    statusClass = 'status-warning';
                } else {
                    statusClass = 'status-danger';
                }
                
                warehouseListElement.innerHTML += `
                    <tr data-code="${warehouse.warehouse_code}">
                        <td>${warehouse.warehouse_code}</td>
                        <td>${warehouse.warehouse_name}</td>
                        <td>${warehouse.location}</td>
                        <td>${parseFloat(warehouse.area).toFixed(2)}</td>
                        <td>${warehouse.manager}</td>
                        <td>${warehouse.contact_phone || '-'}</td>
                        <td><span class="${statusClass}">${warehouse.status}</span></td>
                        <td>
                            <button class="btn-edit-warehouse" data-code="${warehouse.warehouse_code}">编辑</button>
                            <button class="btn-delete-warehouse" data-code="${warehouse.warehouse_code}">删除</button>
                        </td>
                    </tr>
                `;
            });
            
            // 添加编辑和删除按钮事件处理
            document.querySelectorAll('.btn-edit-warehouse').forEach(btn => {
                btn.addEventListener('click', function() {
                    const warehouseCode = this.getAttribute('data-code');
                    editWarehouse(warehouseCode);
                });
            });
            
            document.querySelectorAll('.btn-delete-warehouse').forEach(btn => {
                btn.addEventListener('click', function() {
                    const warehouseCode = this.getAttribute('data-code');
                    if (confirm('确定要删除此仓库吗？')) {
                        deleteWarehouse(warehouseCode);
                    }
                });
            });
        } else {
            warehouseListElement.innerHTML = `<tr><td colspan="8" class="error-message">加载失败：${data.message}</td></tr>`;
        }
    })
    .catch(err => {
        console.error('加载仓库列表失败:', err);
        warehouseListElement.innerHTML = `<tr><td colspan="8" class="error-message">加载失败：${err.message}</td></tr>`;
    });
}

// 编辑仓库
function editWarehouse(warehouseCode) {
    fetch(`/api/warehouses/${warehouseCode}`)
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            const warehouse = data.data;
            
            // 打开编辑弹窗
            moduleContent.innerHTML += `
                <div class="modal" id="edit-warehouse-modal">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h3>编辑仓库信息</h3>
                            <span class="close-modal">&times;</span>
                        </div>
                        <div class="modal-body">
                            <form id="edit-warehouse-form" class="product-form">
                                <div class="form-group">
                                    <label for="edit-warehouse-code">仓库编码</label>
                                    <input type="text" id="edit-warehouse-code" class="form-control" value="${warehouse.warehouse_code}" readonly>
                                </div>
                                
                                <div class="form-group">
                                    <label for="edit-warehouse-name">仓库名称</label>
                                    <input type="text" id="edit-warehouse-name" class="form-control" value="${warehouse.warehouse_name}" required>
                                </div>
                                
                                <div class="form-group">
                                    <label for="edit-warehouse-location">仓库位置</label>
                                    <input type="text" id="edit-warehouse-location" class="form-control" value="${warehouse.location}" required>
                                </div>
                                
                                <div class="form-group">
                                    <label for="edit-warehouse-area">仓库面积(平方米)</label>
                                    <input type="number" id="edit-warehouse-area" class="form-control" value="${warehouse.area}" min="1" step="0.01" required>
                                </div>
                                
                                <div class="form-group">
                                    <label for="edit-warehouse-manager">仓库管理员</label>
                                    <input type="text" id="edit-warehouse-manager" class="form-control" value="${warehouse.manager}" required>
                                </div>
                                
                                <div class="form-group">
                                    <label for="edit-warehouse-contact">联系电话</label>
                                    <input type="text" id="edit-warehouse-contact" class="form-control" value="${warehouse.contact_phone || ''}">
                                </div>
                                
                                <div class="form-group">
                                    <label for="edit-warehouse-status">仓库状态</label>
                                    <select id="edit-warehouse-status" class="form-control" required>
                                        <option value="正常" ${warehouse.status === '正常' ? 'selected' : ''}>正常</option>
                                        <option value="维护中" ${warehouse.status === '维护中' ? 'selected' : ''}>维护中</option>
                                        <option value="已关闭" ${warehouse.status === '已关闭' ? 'selected' : ''}>已关闭</option>
                                    </select>
                                </div>
                                
                                <div class="form-group">
                                    <label for="edit-warehouse-description">仓库描述</label>
                                    <textarea id="edit-warehouse-description" class="form-control">${warehouse.description || ''}</textarea>
                                </div>
                                
                                <div class="form-actions">
                                    <button type="submit" class="btn-save">保存修改</button>
                                    <button type="button" class="btn-cancel">取消</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            `;
            
            // 显示弹窗
            const modal = document.getElementById('edit-warehouse-modal');
            modal.style.display = 'block';
            
            // 关闭弹窗事件
            document.querySelector('.close-modal').addEventListener('click', function() {
                modal.remove();
            });
            
            document.querySelector('.btn-cancel').addEventListener('click', function() {
                modal.remove();
            });
            
            // 表单提交事件
            document.getElementById('edit-warehouse-form').addEventListener('submit', function(e) {
                e.preventDefault();
                
                // 获取修改后的数据
                const updatedData = {
                    warehouse_name: document.getElementById('edit-warehouse-name').value,
                    location: document.getElementById('edit-warehouse-location').value,
                    area: document.getElementById('edit-warehouse-area').value,
                    manager: document.getElementById('edit-warehouse-manager').value,
                    contact_phone: document.getElementById('edit-warehouse-contact').value,
                    status: document.getElementById('edit-warehouse-status').value,
                    description: document.getElementById('edit-warehouse-description').value
                };
                
                // 发送请求更新仓库
                fetch(`/api/warehouses/${warehouseCode}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(updatedData)
                })
                .then(res => res.json())
                .then(data => {
                    if (data.success) {
                        alert('仓库信息更新成功');
                        modal.remove();
                        // 重新加载仓库列表
                        loadWarehouseList();
                    } else {
                        alert('仓库信息更新失败：' + data.message);
                    }
                })
                .catch(err => {
                    console.error('更新仓库请求失败:', err);
                    alert('更新仓库请求失败，请检查网络连接');
                });
            });
        } else {
            alert('获取仓库信息失败：' + data.message);
        }
    })
    .catch(err => {
        console.error('获取仓库信息失败:', err);
        alert('获取仓库信息失败，请检查网络连接');
    });
}

// 删除仓库
function deleteWarehouse(warehouseCode) {
    fetch(`/api/warehouses/${warehouseCode}`, {
        method: 'DELETE'
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            alert('仓库删除成功');
            // 重新加载仓库列表
            loadWarehouseList();
        } else {
            alert('仓库删除失败：' + data.message);
        }
    })
    .catch(err => {
        console.error('删除仓库请求失败:', err);
        alert('删除仓库请求失败，请检查网络连接');
    });
}

// 加载商品入库管理模块
function loadStockInManagement() {
    // 获取商品、仓库和供应商数据
    Promise.all([
        fetch('/api/products').then(res => res.json()),
        fetch('/api/warehouses').then(res => res.json()),
        fetch('/api/suppliers').then(res => res.json())
    ])
    .then(([productsResponse, warehousesResponse, suppliersResponse]) => {
        if (!productsResponse.success || !warehousesResponse.success || !suppliersResponse.success) {
            throw new Error('获取数据失败');
        }
        
        const products = productsResponse.data;
        const warehouses = warehousesResponse.data.filter(warehouse => warehouse.status === '正常');
        const suppliers = suppliersResponse.data;
        
        // 渲染商品入库管理界面
        moduleContent.innerHTML = `
            <div class="module-header">
                <h2>商品入库管理</h2>
                <p>录入商品入库信息，自动更新库存，并保存入库记录</p>
            </div>
            
            <div class="product-form-container">
                <form id="stock-in-form" class="product-form">
                    <div class="form-group">
                        <label for="product-select">选择商品</label>
                        <select id="product-select" class="form-control" required>
                            <option value="">请选择商品</option>
                            ${products.map(product => `<option value="${product.product_code}" data-name="${product.product_name}">${product.product_name} (${product.product_code})</option>`).join('')}
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="warehouse-select">选择仓库</label>
                        <select id="warehouse-select" class="form-control" required>
                            <option value="">请选择仓库</option>
                            ${warehouses.map(warehouse => `<option value="${warehouse.warehouse_code}" data-name="${warehouse.warehouse_name}">${warehouse.warehouse_name} (${warehouse.warehouse_code})</option>`).join('')}
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="quantity">入库数量</label>
                        <input type="number" id="quantity" class="form-control" placeholder="请输入入库数量" min="1" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="batch-number">批次号</label>
                        <input type="text" id="batch-number" class="form-control" placeholder="请输入批次号">
                    </div>
                    
                    <div class="form-group">
                        <label for="production-date">生产日期</label>
                        <input type="date" id="production-date" class="form-control">
                    </div>
                    
                    <div class="form-group">
                        <label for="expiry-date">有效期至</label>
                        <input type="date" id="expiry-date" class="form-control">
                    </div>
                    
                    <div class="form-group">
                        <label for="supplier-select">供应商</label>
                        <select id="supplier-select" class="form-control" required>
                            <option value="">请选择供应商</option>
                            ${suppliers.map(supplier => `<option value="${supplier.name}">${supplier.name}</option>`).join('')}
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="operator">商品成本</label>
                        <input type="number" id="operator" class="form-control" placeholder="请输入商品成本" min="0.01" step="0.01" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="entry-date">入库日期</label>
                        <input type="date" id="entry-date" class="form-control" value="${formatDate(new Date())}" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="note">备注</label>
                        <textarea id="note" class="form-control" placeholder="请输入备注信息"></textarea>
                    </div>
                    
                    <div class="form-actions">
                        <button type="submit" class="btn-save">提交入库</button>
                        <button type="reset" class="btn-reset">重置</button>
                    </div>
                </form>
            </div>
            
            <div class="module-header search-header">
                <h2>入库记录查询</h2>
                <div class="search-bar">
                    <select id="search-warehouse" class="search-select">
                        <option value="">所有仓库</option>
                        ${warehouses.map(warehouse => `<option value="${warehouse.warehouse_code}">${warehouse.warehouse_name}</option>`).join('')}
                    </select>
                    <input type="date" id="search-start-date" class="search-input" placeholder="开始日期">
                    <input type="date" id="search-end-date" class="search-input" placeholder="结束日期">
                    <input type="text" id="search-product" class="search-input" placeholder="商品编码或名称">
                    <button id="search-btn" class="search-btn">查询</button>
                </div>
            </div>
            
            <div class="product-list-container">
                <div class="table-container">
                    <table class="stock-in-table">
                        <thead>
                            <tr>
                                <th>入库单号</th>
                                <th>商品名称</th>
                                <th>仓库</th>
                                <th class="quantity">数量</th>
                                <th class="batch-number">批次号</th>
                                <th>供应商</th>
                                <th class="entry-date">入库日期</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="stock-in-list">
                            <tr>
                                <td colspan="9" class="loading">加载中...</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        `;
        
        // 加载入库记录列表
        loadStockInRecords();
        
        // 添加搜索按钮事件
        document.getElementById('search-btn').addEventListener('click', function() {
            loadStockInRecords();
        });
        
        // 添加表单提交事件处理
        document.getElementById('stock-in-form').addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 获取选中的商品和仓库名称
            const productSelect = document.getElementById('product-select');
            const warehouseSelect = document.getElementById('warehouse-select');
            
            if (!productSelect.value || !warehouseSelect.value) {
                alert('请选择商品和仓库');
                return;
            }
            
            // 获取表单数据
            const stockInData = {
                product_code: productSelect.value,
                warehouse_code: warehouseSelect.value,
                quantity: document.getElementById('quantity').value,
                batch_number: document.getElementById('batch-number').value,
                production_date: document.getElementById('production-date').value,
                expiry_date: document.getElementById('expiry-date').value,
                supplier: document.getElementById('supplier-select').value,
                operator: document.getElementById('operator').value, // 保持字段名不变，但实际存储的是商品成本
                entry_date: document.getElementById('entry-date').value,
                note: document.getElementById('note').value
            };
            
            // 发送请求添加入库记录
            fetch('/api/stock-in-records', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(stockInData)
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    alert('商品入库成功');
                    // 重置表单
                    document.getElementById('stock-in-form').reset();
                    // 重新设置入库日期为今天
                    document.getElementById('entry-date').value = formatDate(new Date());
                    // 重新加载入库记录列表
                    loadStockInRecords();
                } else {
                    alert('商品入库失败：' + data.message);
                }
            })
            .catch(err => {
                console.error('添加入库记录请求失败:', err);
                alert('添加入库记录请求失败，请检查网络连接');
            });
        });
    })
    .catch(err => {
        console.error('加载商品入库管理模块失败:', err);
        moduleContent.innerHTML = `
            <div class="error-message">
                加载商品入库管理模块失败：${err.message}
            </div>
        `;
    });
}

// 加载入库记录列表
function loadStockInRecords() {
    const stockInListElement = document.getElementById('stock-in-list');
    if (!stockInListElement) return;
    
    stockInListElement.innerHTML = '<tr><td colspan="9" class="loading">加载中...</td></tr>';
    
    // 获取搜索条件
    const searchProduct = document.getElementById('search-product')?.value || '';
    const searchWarehouse = document.getElementById('search-warehouse')?.value || '';
    const searchStartDate = document.getElementById('search-start-date')?.value || '';
    const searchEndDate = document.getElementById('search-end-date')?.value || '';
    
    // 构建查询参数
    let url = '/api/stock-in-records';
    let params = [];
    
    if (searchWarehouse) {
        params.push(`warehouse_code=${searchWarehouse}`);
    }
    
    if (searchStartDate) {
        params.push(`start_date=${searchStartDate}`);
    }
    
    if (searchEndDate) {
        params.push(`end_date=${searchEndDate}`);
    }
    
    // 添加参数到URL
    if (params.length > 0) {
        url += '?' + params.join('&');
    }
    
    fetch(url)
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            let records = data.data;
            
            // 如果有商品搜索条件，在前端过滤
            if (searchProduct) {
                records = records.filter(record => 
                    record.product_code.toLowerCase().includes(searchProduct.toLowerCase()) ||
                    record.product_name.toLowerCase().includes(searchProduct.toLowerCase())
                );
            }
            
            if (records.length === 0) {
                stockInListElement.innerHTML = '<tr><td colspan="9" class="no-data">暂无入库记录</td></tr>';
                return;
            }
            
            stockInListElement.innerHTML = '';
            records.forEach(record => {
                stockInListElement.innerHTML += `
                    <tr data-number="${record.record_number}">
                        <td>${record.record_number}</td>
                        <td>${record.product_name}</td>
                        <td>${record.warehouse_name}</td>
                        <td class="quantity">${record.quantity}</td>
                        <td class="batch-number">${record.batch_number || '-'}</td>
                        <td>${record.supplier}</td>
                        <td class="entry-date">${record.entry_date}</td>
                        <td><span class="status-tag status-completed">${record.status}</span></td>
                        <td>
                            <button class="btn-view-stock-in" data-number="${record.record_number}">查看</button>
                            <button class="btn-delete-stock-in" data-number="${record.record_number}">删除</button>
                        </td>
                    </tr>
                `;
            });
            
            // 添加查看和删除按钮事件处理
            document.querySelectorAll('.btn-view-stock-in').forEach(btn => {
                btn.addEventListener('click', function() {
                    const recordNumber = this.getAttribute('data-number');
                    viewStockInRecord(recordNumber);
                });
            });
            
            document.querySelectorAll('.btn-delete-stock-in').forEach(btn => {
                btn.addEventListener('click', function() {
                    const recordNumber = this.getAttribute('data-number');
                    if (confirm('确定要删除此入库记录吗？这将会减少相应商品的库存数量！')) {
                        deleteStockInRecord(recordNumber);
                    }
                });
            });
        } else {
            stockInListElement.innerHTML = `<tr><td colspan="9" class="error-message">加载失败：${data.message}</td></tr>`;
        }
    })
    .catch(err => {
        console.error('加载入库记录失败:', err);
        stockInListElement.innerHTML = `<tr><td colspan="9" class="error-message">加载失败：${err.message}</td></tr>`;
    });
}

// 查看入库记录详情
function viewStockInRecord(recordNumber) {
    fetch(`/api/stock-in-records/${recordNumber}`)
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            const record = data.data;
            
            // 打开详情弹窗
            moduleContent.insertAdjacentHTML('beforeend', `
                <div class="modal-overlay" id="view-stock-in-modal">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h3>入库记录详情</h3>
                            <span class="close-modal">&times;</span>
                        </div>
                        <div class="modal-body">
                            <div class="record-detail">
                                <div class="detail-group">
                                    <div class="detail-item">
                                        <span class="detail-label">入库单号：</span>
                                        <span class="detail-value">${record.record_number}</span>
                                    </div>
                                    <div class="detail-item">
                                        <span class="detail-label">入库状态：</span>
                                        <span class="detail-value status-tag status-completed">${record.status}</span>
                                    </div>
                                </div>
                                
                                <div class="detail-group">
                                    <div class="detail-item">
                                        <span class="detail-label">入库日期：</span>
                                        <span class="detail-value">${record.entry_date}</span>
                                    </div>
                                    <div class="detail-item">
                                        <span class="detail-label">创建时间：</span>
                                        <span class="detail-value">${record.create_time}</span>
                                    </div>
                                </div>
                                
                                <div class="detail-group">
                                    <div class="detail-item">
                                        <span class="detail-label">商品编码：</span>
                                        <span class="detail-value">${record.product_code}</span>
                                    </div>
                                    <div class="detail-item">
                                        <span class="detail-label">商品名称：</span>
                                        <span class="detail-value">${record.product_name}</span>
                                    </div>
                                </div>
                                
                                <div class="detail-group">
                                    <div class="detail-item">
                                        <span class="detail-label">入库数量：</span>
                                        <span class="detail-value">${record.quantity}</span>
                                    </div>
                                    <div class="detail-item">
                                        <span class="detail-label">批次号：</span>
                                        <span class="detail-value">${record.batch_number || '-'}</span>
                                    </div>
                                </div>
                                
                                <div class="detail-group">
                                    <div class="detail-item">
                                        <span class="detail-label">仓库编码：</span>
                                        <span class="detail-value">${record.warehouse_code}</span>
                                    </div>
                                    <div class="detail-item">
                                        <span class="detail-label">仓库名称：</span>
                                        <span class="detail-value">${record.warehouse_name}</span>
                                    </div>
                                </div>
                                
                                <div class="detail-group">
                                    <div class="detail-item">
                                        <span class="detail-label">生产日期：</span>
                                        <span class="detail-value">${record.production_date || '-'}</span>
                                    </div>
                                    <div class="detail-item">
                                        <span class="detail-label">有效期至：</span>
                                        <span class="detail-value">${record.expiry_date || '-'}</span>
                                    </div>
                                </div>
                                
                                <div class="detail-group">
                                    <div class="detail-item">
                                        <span class="detail-label">供应商：</span>
                                        <span class="detail-value">${record.supplier}</span>
                                    </div>
                                    <div class="detail-item">
                                        <span class="detail-label">商品成本 (¥)：</span>
                                        <span class="detail-value">¥${parseFloat(record.operator).toFixed(2)}</span>
                                    </div>
                                </div>
                                
                                <div class="detail-group full-width">
                                    <div class="detail-item">
                                        <span class="detail-label">备注信息：</span>
                                        <span class="detail-value">${record.note || '无'}</span>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="form-actions">
                                <button type="button" class="btn-cancel">关闭</button>
                            </div>
                        </div>
                    </div>
                </div>
            `);
            
            // 显示弹窗
            const modal = document.getElementById('view-stock-in-modal');
            modal.style.display = 'block';
            
            // 关闭弹窗事件
            document.querySelector('.close-modal').addEventListener('click', function() {
                modal.remove();
                loadStockInRecords(); // 关闭后刷新主表，重新绑定事件
            });
            
            document.querySelector('.btn-cancel').addEventListener('click', function() {
                modal.remove();
                loadStockInRecords(); // 关闭后刷新主表，重新绑定事件
            });
        } else {
            alert('获取入库记录详情失败：' + data.message);
        }
    })
    .catch(err => {
        console.error('获取入库记录详情失败:', err);
        alert('获取入库记录详情失败，请检查网络连接');
    });
}

// 删除入库记录
function deleteStockInRecord(recordNumber) {
    fetch(`/api/stock-in-records/${recordNumber}`, {
        method: 'DELETE'
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            alert('入库记录删除成功');
            // 重新加载入库记录列表
            loadStockInRecords();
        } else {
            alert('入库记录删除失败：' + data.message);
        }
    })
    .catch(err => {
        console.error('删除入库记录请求失败:', err);
        alert('删除入库记录请求失败，请检查网络连接');
    });
}

// 添加商品出库管理模块
function loadStockOutModule() {
    // 显示加载状态
    moduleContent.innerHTML = '<div class="loading">加载中...</div>';
    
    // 获取商品、仓库和供应商数据
    Promise.all([
        fetch('/api/products').then(res => res.json()),
        fetch('/api/warehouses').then(res => res.json()),
        fetch('/api/stock-out-records').then(res => res.json())
    ])
    .then(([productsResponse, warehousesResponse, stockOutResponse]) => {
        if (!productsResponse.success || !warehousesResponse.success) {
            throw new Error('获取数据失败');
        }
        
        const products = productsResponse.data;
        const warehouses = warehousesResponse.data.filter(warehouse => warehouse.status === '正常');
        window.warehouses = warehouses; // 新增这一行
        const stockOutRecords = stockOutResponse.records || [];
        // 修正：根据warehouse_code补全/更新每条记录的warehouse_name，确保显示最新仓库名
        stockOutRecords.forEach(record => {
            const warehouse = warehouses.find(w => w.warehouse_code === record.warehouse_code);
            record.warehouse_name = warehouse ? warehouse.warehouse_name : record.warehouse_code;
        });
        
        // 渲染商品出库管理界面
        moduleContent.innerHTML = `
            <div class="module-header">
                <h2>商品出库管理</h2>
                <p>管理超市商品的出库操作，记录出库情况，自动更新库存</p>
            </div>
            
            <button id="add-stock-out-btn" class="add-stock-out-btn">
                <i>+</i> 新增出库记录
            </button>
            
            <div class="filter-section">
                <div class="search-bar">
                    <select id="warehouse-filter" class="search-select">
                        <option value="">全部仓库</option>
                        ${warehouses.map(warehouse => `
                            <option value="${warehouse.warehouse_code}">${warehouse.warehouse_name}</option>
                        `).join('')}
                    </select>
                    <input type="date" id="start-date-filter" class="search-input" placeholder="开始日期">
                    <input type="date" id="end-date-filter" class="search-input" placeholder="结束日期">
                    <input type="text" id="product-search" class="search-input" placeholder="搜索商品名称/编码">
                    <button id="search-btn" class="search-btn">搜索</button>
                    <button id="reset-btn" class="btn-reset">重置</button>
                </div>
            </div>
            
            <div class="table-container">
                <table class="stock-out-table">
                    <thead>
                        <tr>
                            <th>出库单号</th>
                            <th>商品编码</th>
                            <th>商品名称</th>
                            <th>仓库</th>
                            <th>数量</th>
                            <th>批次号</th>
                            <th>出库原因</th>
                            <th>接收方</th>
                            <th>操作人员</th>
                            <th>出库日期</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="stock-out-table-body">
                        ${stockOutRecords.length > 0 ? stockOutRecords.map(record => `
                            <tr>
                                <td>${record.record_number}</td>
                                <td>${record.product_code}</td>
                                <td>${record.product_name}</td>
                                <td>${record.warehouse_name}</td>
                                <td class="quantity">${record.quantity}</td>
                                <td class="batch-number">${record.batch_number || '-'}</td>
                                <td>
                                    <span class="reason-tag reason-${getReasonClass(record.out_reason)}">
                                        ${record.out_reason}
                                    </span>
                                </td>
                                <td>${record.recipient}</td>
                                <td>${record.operator}</td>
                                <td class="out-date">${record.out_date}</td>
                                <td>${record.status}</td>
                                <td>
                                    <button class="btn-edit-stock-out" data-record="${record.record_number}">编辑</button>
                                    <button class="btn-delete-stock-out" data-record="${record.record_number}">删除</button>
                                </td>
                            </tr>
                        `).join('') : `
                            <tr>
                                <td colspan="12" class="no-data">暂无出库记录</td>
                            </tr>
                        `}
                    </tbody>
                </table>
            </div>
        `;
        
        // 获取出库原因样式类
        function getReasonClass(reason) {
            const reasonMap = {
                '销售': 'sales',
                '损坏': 'damaged',
                '过期': 'expired',
                '调拨': 'transfer',
                '其他': 'other'
            };
            return reasonMap[reason] || 'other';
        }
        
        // 添加出库记录按钮事件
        const addStockOutBtn = document.getElementById('add-stock-out-btn');
        addStockOutBtn.addEventListener('click', () => {
            // 如果已存在弹窗则不再弹出
            if (document.getElementById('add-stock-out-modal')) return;
            addStockOutBtn.disabled = true;
            showAddStockOutModal(products, warehouses, () => {
                addStockOutBtn.disabled = false;
            });
        });
        
        // 搜索按钮事件
        document.getElementById('search-btn').addEventListener('click', () => {
            searchStockOutRecords();
        });
        
        // 重置按钮事件
        document.getElementById('reset-btn').addEventListener('click', () => {
            document.getElementById('warehouse-filter').value = '';
            document.getElementById('start-date-filter').value = '';
            document.getElementById('end-date-filter').value = '';
            document.getElementById('product-search').value = '';
            loadStockOutModule();
        });
        
        // 编辑、删除按钮事件
        document.querySelectorAll('.btn-edit-stock-out').forEach(button => {
            button.addEventListener('click', () => {
                if (document.getElementById('edit-stock-out-modal')) return;
                button.disabled = true;
                const recordNumber = button.dataset.record;
                editStockOutRecord(recordNumber, products, warehouses, () => {
                    button.disabled = false;
                });
            });
        });
        
        document.querySelectorAll('.btn-delete-stock-out').forEach(button => {
            button.addEventListener('click', () => {
                const recordNumber = button.dataset.record;
                if (confirm('确定要删除此出库记录吗？这将会增加相应商品的库存数量！')) {
                    deleteStockOutRecord(recordNumber);
                }
            });
        });
    })
    .catch(error => {
        console.error('加载商品出库管理模块失败:', error);
        moduleContent.innerHTML = `
            <div class="error-message">
                加载商品出库管理模块失败: ${error.message}
            </div>
        `;
    });
}

// 搜索出库记录
function searchStockOutRecords() {
    const warehouseCode = document.getElementById('warehouse-filter').value;
    const startDate = document.getElementById('start-date-filter').value;
    const endDate = document.getElementById('end-date-filter').value;
    const productSearch = document.getElementById('product-search').value;
    
    // 构建查询参数
    const params = new URLSearchParams();
    if (warehouseCode) params.append('warehouse_code', warehouseCode);
    if (startDate) params.append('start_date', startDate);
    if (endDate) params.append('end_date', endDate);
    if (productSearch) params.append('product_code', productSearch);
    
    // 发送请求获取筛选后的数据
    fetch(`/api/stock-out-records?${params.toString()}`)
    .then(res => res.json())
    .then(response => {
        const stockOutRecords = response.records || [];
        updateStockOutTable(stockOutRecords);
    })
    .catch(error => {
        console.error('搜索出库记录失败:', error);
        showNotification('搜索出库记录失败', 'error');
    });
}

// 更新出库记录表格
function updateStockOutTable(records) {
    // 获取仓库列表（优先用全局window.warehouses，否则重新拉取）
    let warehouses = window.warehouses;
    if (!warehouses) {
        try {
            const xhr = new XMLHttpRequest();
            xhr.open('GET', '/api/warehouses', false);
            xhr.send(null);
            if (xhr.status === 200) {
                const res = JSON.parse(xhr.responseText);
                warehouses = res.data ? res.data.filter(w => w.status === '正常') : [];
            } else {
                warehouses = [];
            }
        } catch (e) {
            warehouses = [];
        }
    }
    // 补全每条记录的warehouse_name
    records.forEach(record => {
        const warehouse = warehouses.find(w => w.warehouse_code === record.warehouse_code);
        record.warehouse_name = warehouse ? warehouse.warehouse_name : record.warehouse_code;
    });
    
    const tableBody = document.getElementById('stock-out-table-body');
    
    if (records.length === 0) {
        tableBody.innerHTML = `
            <tr>
                <td colspan="12" class="no-data">暂无出库记录</td>
            </tr>
        `;
        return;
    }
    
    tableBody.innerHTML = records.map(record => `
        <tr>
            <td>${record.record_number}</td>
            <td>${record.product_code}</td>
            <td>${record.product_name}</td>
            <td>${record.warehouse_name}</td>
            <td class="quantity">${record.quantity}</td>
            <td class="batch-number">${record.batch_number || '-'}</td>
            <td>
                <span class="reason-tag reason-${getReasonClass(record.out_reason)}">
                    ${record.out_reason}
                </span>
            </td>
            <td>${record.recipient}</td>
            <td>${record.operator}</td>
            <td class="out-date">${record.out_date}</td>
            <td>${record.status}</td>
            <td>
                <button class="btn-edit-stock-out" data-record="${record.record_number}">编辑</button>
                <button class="btn-delete-stock-out" data-record="${record.record_number}">删除</button>
            </td>
        </tr>
    `).join('');
    
    // 重新绑定按钮事件
    document.querySelectorAll('.btn-edit-stock-out').forEach(button => {
        button.addEventListener('click', () => {
            editStockOutRecord(button.dataset.record);
        });
    });
    
    document.querySelectorAll('.btn-delete-stock-out').forEach(button => {
        button.addEventListener('click', () => {
            deleteStockOutRecord(button.dataset.record);
        });
    });
    
    // 获取出库原因样式类
    function getReasonClass(reason) {
        const reasonMap = {
            '销售': 'sales',
            '损坏': 'damage',
            '过期': 'expired',
            '调拨': 'transfer'
        };
        return reasonMap[reason] || 'other';
    }
}

// 改进添加出库记录模态框，使其更加直观友好
function showAddStockOutModal(products, warehouses, onClose) {
    moduleContent.insertAdjacentHTML('beforeend', `
        <div class="modal stock-out-modal" id="add-stock-out-modal">
            <div class="modal-content">
                <div class="modal-header">
                    <h3>添加出库记录</h3>
                    <span class="close-modal">&times;</span>
                </div>
                <div class="modal-body">
                    <form id="add-stock-out-form" class="stock-out-form">
                        <div class="form-group">
                            <label for="product">商品：</label>
                            <select id="product" name="product_code" class="form-control" required>
                                <option value="">请选择商品</option>
                                ${products.filter(product => product.current_stock > 0).map(product => `
                                    <option value="${product.product_code}" data-name="${product.product_name}" data-stock="${product.current_stock}">
                                        ${product.product_name} (库存:${product.current_stock})
                                    </option>
                                `).join('')}
                            </select>
                            <span class="stock-hint" id="product-hint"></span>
                        </div>
                        <div class="form-group">
                            <label for="warehouse">仓库：</label>
                            <select id="warehouse" name="warehouse_code" class="form-control" required>
                                <option value="">请选择仓库</option>
                                ${warehouses.map(warehouse => `
                                    <option value="${warehouse.warehouse_code}" data-name="${warehouse.warehouse_name}">
                                        ${warehouse.warehouse_name}
                                    </option>
                                `).join('')}
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="quantity">数量：</label>
                            <input type="number" id="quantity" name="quantity" class="form-control" min="1" required>
                            <span class="stock-hint" id="stock-hint"></span>
                        </div>
                        <div class="form-group">
                            <label for="batch_number">批次号：</label>
                            <input type="text" id="batch_number" name="batch_number" class="form-control" placeholder="可选">
                        </div>
                        <div class="form-group">
                            <label for="out_reason">出库原因：</label>
                            <select id="out_reason" name="out_reason" class="form-control" required>
                                <option value="">请选择出库原因</option>
                                <option value="销售">销售</option>
                                <option value="损坏">损坏</option>
                                <option value="过期">过期</option>
                                <option value="调拨">调拨</option>
                                <option value="其他">其他</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="recipient">接收方：</label>
                            <input type="text" id="recipient" name="recipient" class="form-control" required placeholder="请输入接收方名称">
                        </div>
                        <div class="form-group">
                            <label for="operator">操作人员：</label>
                            <input type="text" id="operator" name="operator" class="form-control" required placeholder="请输入操作人员姓名">
                        </div>
                        <div class="form-group">
                            <label for="out_date">出库日期：</label>
                            <input type="date" id="out_date" name="out_date" class="form-control" value="${new Date().toISOString().substr(0, 10)}" required>
                        </div>
                        <div class="form-group" style="grid-column: span 2;">
                            <label for="note">备注：</label>
                            <textarea id="note" name="note" class="form-control" placeholder="请输入备注信息（可选）"></textarea>
                        </div>
                        <div class="form-actions">
                            <button type="button" class="btn-secondary cancel-btn">取消</button>
                            <button type="submit" class="btn-primary">保存</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    `);
    
    // 显示模态框并添加淡入效果
    const modal = document.getElementById('add-stock-out-modal');
    modal.style.display = 'block';
    setTimeout(() => {
        modal.style.opacity = '1';
    }, 10);
    
    // 关闭模态框
    const closeModal = modal.querySelector('.close-modal');
    const cancelBtn = modal.querySelector('.cancel-btn');
    
    function hideAndRemoveModal() {
        modal.style.opacity = '0';
        setTimeout(() => {
            modal.remove();
            if (typeof onClose === 'function') onClose();
        }, 300);
    }
    
    closeModal.addEventListener('click', hideAndRemoveModal);
    cancelBtn.addEventListener('click', hideAndRemoveModal);
    
    // 商品选择时更新库存提示
    const productSelect = document.getElementById('product');
    const quantityInput = document.getElementById('quantity');
    const stockHint = document.getElementById('stock-hint');
    const productHint = document.getElementById('product-hint');
    
    productSelect.addEventListener('change', () => {
        const selectedOption = productSelect.options[productSelect.selectedIndex];
        if (selectedOption.value) {
            const productName = selectedOption.dataset.name;
            const currentStock = selectedOption.dataset.stock;
            stockHint.textContent = `可用库存：${currentStock}`;
            stockHint.style.color = currentStock < 10 ? '#e74c3c' : '#27ae60';
            quantityInput.max = currentStock;
            quantityInput.min = 1;
            quantityInput.value = '';
            productHint.textContent = '';
        } else {
            stockHint.textContent = '';
            productHint.textContent = '请选择一个商品';
        }
    });
    
    // 数量输入验证
    quantityInput.addEventListener('input', () => {
        const selectedOption = productSelect.options[productSelect.selectedIndex];
        if (selectedOption.value) {
            const currentStock = parseInt(selectedOption.dataset.stock);
            const quantity = parseInt(quantityInput.value);
            
            if (quantity > currentStock) {
                stockHint.textContent = `超出可用库存！最大可出库数量：${currentStock}`;
                stockHint.style.color = '#e74c3c';
                quantityInput.setCustomValidity('数量超出可用库存');
            } else if (quantity <= 0) {
                stockHint.textContent = '出库数量必须大于0';
                stockHint.style.color = '#e74c3c';
                quantityInput.setCustomValidity('出库数量必须大于0');
            } else {
                stockHint.textContent = `可用库存：${currentStock}`;
                stockHint.style.color = currentStock < 10 ? '#e74c3c' : '#27ae60';
                quantityInput.setCustomValidity('');
            }
        }
    });
    
    // 表单提交
    const form = document.getElementById('add-stock-out-form');
    form.addEventListener('submit', (e) => {
        e.preventDefault();
        
        // 表单验证
        const selectedProduct = productSelect.options[productSelect.selectedIndex];
        if (!selectedProduct.value) {
            productHint.textContent = '请选择一个商品';
            productSelect.focus();
            return;
        }
        
        // 获取表单数据
        const formData = new FormData(form);
        const data = {
            product_code: formData.get('product_code'),
            warehouse_code: formData.get('warehouse_code'),
            quantity: parseInt(formData.get('quantity')),
            batch_number: formData.get('batch_number'),
            out_reason: formData.get('out_reason'),
            recipient: formData.get('recipient'),
            operator: formData.get('operator'),
            out_date: formData.get('out_date'),
            note: formData.get('note'),
            status: '已出库'
        };
        
        // 显示提交中的状态
        const submitBtn = form.querySelector('button[type="submit"]');
        const originalBtnText = submitBtn.textContent;
        submitBtn.textContent = '保存中...';
        submitBtn.disabled = true;
        
        // 发送请求添加出库记录
        fetch('/api/stock-out-records', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        })
        .then(res => res.json())
        .then(response => {
            if (response.success) {
                showNotification(response.message || '出库记录添加成功', 'success');
                hideAndRemoveModal();
                loadStockOutModule(); // 重新加载模块
            } else {
                showNotification(response.message || '添加失败', 'error');
                submitBtn.textContent = originalBtnText;
                submitBtn.disabled = false;
            }
        })
        .catch(error => {
            console.error('添加出库记录失败:', error);
            showNotification('添加出库记录失败', 'error');
            submitBtn.textContent = originalBtnText;
            submitBtn.disabled = false;
        });
    });
}

// 删除出库记录
function deleteStockOutRecord(recordNumber) {
    // 显示确认对话框
    if (confirm('确定要删除这条出库记录吗？此操作将会恢复相应商品的库存数量。')) {
        // 发送请求删除出库记录
        fetch(`/api/stock-out-records/${recordNumber}`, {
            method: 'DELETE'
        })
        .then(res => res.json())
        .then(response => {
            if (response.success) {
                showNotification(response.message || '出库记录删除成功', 'success');
                loadStockOutModule(); // 重新加载模块
            } else {
                showNotification(response.message || '删除失败', 'error');
            }
        })
        .catch(error => {
            console.error('删除出库记录失败:', error);
            showNotification('删除出库记录失败', 'error');
        });
    }
}

// 修改侧边栏菜单加载函数，添加商品出库管理模块
function loadSidebar() {
    const sidebar = document.getElementById('sidebar');
    
    sidebar.innerHTML = `
        <div class="sidebar-header">
            <h3>超市管理系统</h3>
        </div>
        <ul class="sidebar-menu">
            <li class="menu-item" data-module="dashboard">
                <i class="fas fa-home"></i>
                <span>首页</span>
            </li>
            <li class="menu-item has-submenu">
                <div class="menu-title">
                    <i class="fas fa-box"></i>
                    <span>商品管理</span>
                    <i class="fas fa-chevron-down"></i>
                </div>
                <ul class="submenu">
                    <li class="submenu-item" data-module="productInfo">商品信息管理</li>
                    <li class="submenu-item" data-module="categories">商品分类管理</li>
                    <li class="submenu-item" data-module="pricing">商品价格管理</li>
                </ul>
            </li>
            <li class="menu-item has-submenu">
                <div class="menu-title">
                    <i class="fas fa-warehouse"></i>
                    <span>仓储管理</span>
                    <i class="fas fa-chevron-down"></i>
                </div>
                <ul class="submenu">
                    <li class="submenu-item" data-module="warehouses">仓库管理</li>
                    <li class="submenu-item" data-module="stockIn">商品入库管理</li>
                    <li class="submenu-item" data-module="stockOut">商品出库管理</li>
                    <li class="submenu-item" data-module="inventory">库存盘点预警</li>
                </ul>
            </li>
            <li class="menu-item has-submenu">
                <div class="menu-title">
                    <i class="fas fa-tags"></i>
                    <span>营销管理</span>
                    <i class="fas fa-chevron-down"></i>
                </div>
                <ul class="submenu">
                    <li class="submenu-item" data-module="promotions">促销活动管理</li>
                </ul>
            </li>
            <li class="menu-item has-submenu">
                <div class="menu-title">
                    <i class="fas fa-truck"></i>
                    <span>供应商管理</span>
                    <i class="fas fa-chevron-down"></i>
                </div>
                <ul class="submenu">
                    <li class="submenu-item" data-module="suppliers">供应商信息管理</li>
                </ul>
            </li>
            <li class="menu-item has-submenu">
                <div class="menu-title">
                    <i class="fas fa-users"></i>
                    <span>会员管理</span>
                    <i class="fas fa-chevron-down"></i>
                </div>
                <ul class="submenu">
                    <li class="submenu-item" data-module="memberManagement">会员信息管理</li>
                </ul>
            </li>
            <li class="menu-item has-submenu">
                <div class="menu-title">
                    <i class="fas fa-cog"></i>
                    <span>系统设置</span>
                    <i class="fas fa-chevron-down"></i>
                </div>
                <ul class="submenu">
                    <li class="submenu-item" data-module="users">用户管理</li>
                    <li class="submenu-item" data-module="roles">角色权限管理</li>
                </ul>
            </li>
        </ul>
    `;
    
    // 折叠/展开子菜单
    const menuTitles = document.querySelectorAll('.menu-title');
    menuTitles.forEach(title => {
        title.addEventListener('click', () => {
            const menuItem = title.parentElement;
            menuItem.classList.toggle('active');
        });
    });
    
    // 加载模块
    const menuItems = document.querySelectorAll('.menu-item:not(.has-submenu), .submenu-item');
    menuItems.forEach(item => {
        item.addEventListener('click', () => {
            // 移除所有活动状态
            menuItems.forEach(i => i.classList.remove('active'));
            
            // 添加活动状态
            item.classList.add('active');
            
            // 加载对应模块
            const module = item.dataset.module;
            loadModule(module);
        });
    });
}

// 修改加载模块的函数，添加商品出库管理模块
function loadModule(module) {
    moduleContent.innerHTML = '<div class="loading">加载中...</div>';
    
    // 根据模块名称加载对应内容
    switch (module) {
        // ... existing code ...
        case 'stockIn':
            loadStockInManagement();
            break;
        case 'stockOut':
            loadStockOutModule();
            break;
        case 'checkout':
            loadCheckoutModule();
            break;
        case 'report':
            loadSalesStatisticsModule();
            break;
        case 'cost':
            loadCostModule();
            break;
        case 'tax':
            loadTaxModule();
            break;
        case 'memberManagement':
            loadModuleFromHTML('member-register');
            break;
        case 'pointsExchange':
            loadPointsExchangeModule();
            break;
        // ... existing code ...
        default:
            loadDashboard();
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', init); 

// 改进显示编辑出库记录模态框
function showEditStockOutModal(record, products, warehouses, onClose) {
    // 创建模态框
    moduleContent.insertAdjacentHTML('beforeend', `
        <div class="modal stock-out-modal" id="edit-stock-out-modal">
            <div class="modal-content">
                <div class="modal-header">
                    <h3>编辑出库记录 - ${record.record_number}</h3>
                    <span class="close-modal">&times;</span>
                </div>
                <div class="modal-body">
                    <form id="edit-stock-out-form" class="stock-out-form">
                        <div class="form-group">
                            <label for="product">商品：</label>
                            <select id="product" name="product_code" class="form-control" required>
                                <option value="">请选择商品</option>
                                ${products.map(product => {
                                    // 计算可选最大库存：当前库存 + 如果是同一商品则加上原出库数量
                                    const maxStock = product.product_code === record.product_code 
                                        ? parseInt(product.current_stock) + parseInt(record.quantity)
                                        : product.current_stock;
                                    return `
                                        <option value="${product.product_code}" 
                                            data-name="${product.product_name}" 
                                            data-stock="${maxStock}"
                                            data-original="${product.product_code === record.product_code ? 'yes' : 'no'}"
                                            ${product.product_code === record.product_code ? 'selected' : ''}>
                                            ${product.product_name} (可用库存:${maxStock})
                                        </option>
                                    `;
                                }).join('')}
                            </select>
                            <span class="stock-hint" id="product-hint"></span>
                        </div>
                        <div class="form-group">
                            <label for="warehouse">仓库：</label>
                            <select id="warehouse" name="warehouse_code" class="form-control" required>
                                <option value="">请选择仓库</option>
                                ${warehouses.map(warehouse => `
                                    <option value="${warehouse.warehouse_code}" 
                                        data-name="${warehouse.warehouse_name}"
                                        ${warehouse.warehouse_code === record.warehouse_code ? 'selected' : ''}>
                                        ${warehouse.warehouse_name}
                                    </option>
                                `).join('')}
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="quantity">数量：</label>
                            <input type="number" id="quantity" name="quantity" class="form-control" 
                                min="1" value="${record.quantity}" required>
                            <span class="stock-hint" id="stock-hint">
                                可用库存：${products.find(p => p.product_code === record.product_code).current_stock + parseInt(record.quantity)}
                            </span>
                        </div>
                        <div class="form-group">
                            <label for="batch_number">批次号：</label>
                            <input type="text" id="batch_number" name="batch_number" 
                                class="form-control" value="${record.batch_number || ''}" placeholder="可选">
                        </div>
                        <div class="form-group">
                            <label for="out_reason">出库原因：</label>
                            <select id="out_reason" name="out_reason" class="form-control" required>
                                <option value="">请选择出库原因</option>
                                <option value="销售" ${record.out_reason === '销售' ? 'selected' : ''}>销售</option>
                                <option value="损坏" ${record.out_reason === '损坏' ? 'selected' : ''}>损坏</option>
                                <option value="过期" ${record.out_reason === '过期' ? 'selected' : ''}>过期</option>
                                <option value="调拨" ${record.out_reason === '调拨' ? 'selected' : ''}>调拨</option>
                                <option value="其他" ${record.out_reason === '其他' ? 'selected' : ''}>其他</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="recipient">接收方：</label>
                            <input type="text" id="recipient" name="recipient" 
                                class="form-control" value="${record.recipient}" required>
                        </div>
                        <div class="form-group">
                            <label for="operator">操作人员：</label>
                            <input type="text" id="operator" name="operator" 
                                class="form-control" value="${record.operator}" required>
                        </div>
                        <div class="form-group">
                            <label for="out_date">出库日期：</label>
                            <input type="date" id="out_date" name="out_date" 
                                class="form-control" value="${record.out_date}" required>
                        </div>
                        <div class="form-group" style="grid-column: span 2;">
                            <label for="note">备注：</label>
                            <textarea id="note" name="note" class="form-control" 
                                placeholder="请输入备注信息（可选）">${record.note || ''}</textarea>
                        </div>
                        <div class="form-actions">
                            <button type="button" class="btn-secondary cancel-btn">取消</button>
                            <button type="submit" class="btn-primary">保存修改</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    `);
    
    // 显示模态框并添加淡入效果
    const modal = document.getElementById('edit-stock-out-modal');
    modal.style.display = 'block';
    setTimeout(() => {
        modal.style.opacity = '1';
    }, 10);
    
    // 关闭模态框
    const closeModal = modal.querySelector('.close-modal');
    const cancelBtn = modal.querySelector('.cancel-btn');
    
    function hideAndRemoveModal() {
        modal.style.opacity = '0';
        setTimeout(() => {
            modal.remove();
        }, 300);
    }
    
    closeModal.addEventListener('click', hideAndRemoveModal);
    cancelBtn.addEventListener('click', hideAndRemoveModal);
    
    // 商品选择时更新库存提示
    const productSelect = document.getElementById('product');
    const quantityInput = document.getElementById('quantity');
    const stockHint = document.getElementById('stock-hint');
    
    // 存储原始商品和数量
    const originalProductCode = record.product_code;
    const originalQuantity = parseInt(record.quantity);
    
    productSelect.addEventListener('change', () => {
        const selectedOption = productSelect.options[productSelect.selectedIndex];
        if (selectedOption.value) {
            const isOriginalProduct = selectedOption.dataset.original === 'yes';
            const maxStock = parseInt(selectedOption.dataset.stock);
            stockHint.textContent = `可用库存：${maxStock}`;
            stockHint.style.color = maxStock < 10 ? '#e74c3c' : '#27ae60';
            quantityInput.max = maxStock;
            quantityInput.min = 1;
            
            if (!isOriginalProduct) {
                // 如果选择了不同的商品，重置数量输入
                quantityInput.value = 1;
            }
        } else {
            stockHint.textContent = '';
        }
    });
    
    // 数量输入验证
    quantityInput.addEventListener('input', () => {
        const selectedOption = productSelect.options[productSelect.selectedIndex];
        if (selectedOption.value) {
            const isOriginalProduct = selectedOption.dataset.original === 'yes';
            const maxStock = parseInt(selectedOption.dataset.stock);
            const quantity = parseInt(quantityInput.value);
            
            if (quantity > maxStock) {
                stockHint.textContent = `超出可用库存！最大可出库数量：${maxStock}`;
                stockHint.style.color = '#e74c3c';
                quantityInput.setCustomValidity('数量超出可用库存');
            } else if (quantity <= 0) {
                stockHint.textContent = '出库数量必须大于0';
                stockHint.style.color = '#e74c3c';
                quantityInput.setCustomValidity('出库数量必须大于0');
            } else {
                stockHint.textContent = `可用库存：${maxStock}`;
                stockHint.style.color = maxStock < 10 ? '#e74c3c' : '#27ae60';
                quantityInput.setCustomValidity('');
            }
        }
    });
    
    // 表单提交
    const form = document.getElementById('edit-stock-out-form');
    form.addEventListener('submit', (e) => {
        e.preventDefault();
        
        // 获取表单数据
        const formData = new FormData(form);
        const data = {
            product_code: formData.get('product_code'),
            warehouse_code: formData.get('warehouse_code'),
            quantity: parseInt(formData.get('quantity')),
            batch_number: formData.get('batch_number'),
            out_reason: formData.get('out_reason'),
            recipient: formData.get('recipient'),
            operator: formData.get('operator'),
            out_date: formData.get('out_date'),
            note: formData.get('note')
        };
        
        // 显示提交中的状态
        const submitBtn = form.querySelector('button[type="submit"]');
        const originalBtnText = submitBtn.textContent;
        submitBtn.textContent = '保存中...';
        submitBtn.disabled = true;
        
        // 发送请求更新出库记录
        fetch(`/api/stock-out-records/${record.record_number}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        })
        .then(res => res.json())
        .then(response => {
            if (response.success) {
                showNotification(response.message || '出库记录更新成功', 'success');
                hideAndRemoveModal();
                loadStockOutModule(); // 重新加载模块
            } else {
                showNotification(response.message || '更新失败', 'error');
                submitBtn.textContent = originalBtnText;
                submitBtn.disabled = false;
            }
        })
        .catch(error => {
            console.error('更新出库记录失败:', error);
            showNotification('更新出库记录失败', 'error');
            submitBtn.textContent = originalBtnText;
            submitBtn.disabled = false;
        });
    });
}

// 原查看出库记录详情功能已移除
function viewStockOutRecord(recordNumber) {
    // 该功能已被禁用
    console.log('查看出库记录功能已被禁用');
}

// 编辑出库记录函数
function editStockOutRecord(recordNumber, products, warehouses, onClose) {
    // 如果没有传入products和warehouses，需要先获取数据
    if (!products || !warehouses) {
        Promise.all([
            fetch('/api/products').then(res => res.json()),
            fetch('/api/warehouses').then(res => res.json()),
            fetch(`/api/stock-out-records/${recordNumber}`).then(res => res.json())
        ])
        .then(([productsResponse, warehousesResponse, recordResponse]) => {
            if (productsResponse.success && warehousesResponse.success && recordResponse.success) {
                const products = productsResponse.data;
                const warehouses = warehousesResponse.data.filter(warehouse => warehouse.status === '正常');
                const record = recordResponse.record;
                showEditStockOutModal(record, products, warehouses, onClose);
            } else {
                showNotification('获取数据失败', 'error');
                if (typeof onClose === 'function') onClose();
            }
        })
        .catch(error => {
            console.error('获取数据失败:', error);
            showNotification('获取数据失败', 'error');
            if (typeof onClose === 'function') onClose();
        });
        return;
    }
    
    // 如果已经有products和warehouses，则只需要获取记录详情
    fetch(`/api/stock-out-records/${recordNumber}`)
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            showEditStockOutModal(data.record, products, warehouses, onClose);
        } else {
            showNotification(data.message || '获取出库记录详情失败', 'error');
            if (typeof onClose === 'function') onClose();
        }
    })
    .catch(error => {
        console.error('获取出库记录详情失败:', error);
        showNotification('获取出库记录详情失败', 'error');
        if (typeof onClose === 'function') onClose();
    });
}

// 显示添加预警设置模态框
function showAddAlertModal() {
    // 获取所有未设置预警的商品
    fetch('/api/products/without-alerts')
    .then(res => res.json())
    .then(data => {
        if (!data.success) {
            throw new Error('获取商品数据失败');
        }
        
        const products = data.data;
        
        if (products.length === 0) {
            showNotification('没有可添加预警设置的商品', 'warning');
            return;
        }
        
        // 创建模态框
        moduleContent.innerHTML += `
            <div class="modal inventory-modal" id="add-alert-modal">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3>添加库存预警设置</h3>
                        <span class="close-modal">&times;</span>
                    </div>
                    <div class="modal-body">
                        <form id="add-alert-form" class="inventory-form">
                            <div class="form-group">
                                <label for="product-select">选择商品：</label>
                                <select id="product-select" class="form-control" required>
                                    <option value="">请选择商品</option>
                                    ${products.map(product => `
                                        <option value="${product.product_code}" 
                                            data-name="${product.product_name}" 
                                            data-category="${product.category}" 
                                            data-stock="${product.current_stock}">
                                            ${product.product_name} (${product.product_code}) - 当前库存: ${product.current_stock}
                                        </option>
                                    `).join('')}
                                </select>
                            </div>
                            
                            <div class="form-group">
                                <label for="min-stock">安全库存下限：</label>
                                <input type="number" id="min-stock" class="form-control" min="0" required>
                                <span class="form-hint">当库存低于此值时将发出预警</span>
                            </div>
                            
                            <div class="form-group">
                                <label for="max-stock">库存上限：</label>
                                <input type="number" id="max-stock" class="form-control" min="0" required>
                                <span class="form-hint">当库存高于此值时将显示为库存积压</span>
                            </div>
                            
                            <div class="form-group">
                                <label for="alert-enabled">启用预警：</label>
                                <div class="toggle-switch">
                                    <input type="checkbox" id="alert-enabled" checked>
                                    <label for="alert-enabled"></label>
                                </div>
                            </div>
                            
                            <div class="form-actions">
                                <button type="button" class="btn-cancel">取消</button>
                                <button type="submit" class="btn-save">保存</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        `;
        
        // 显示模态框
        const modal = document.getElementById('add-alert-modal');
        modal.style.display = 'block';
        
        // 关闭模态框事件
        const closeBtn = modal.querySelector('.close-modal');
        const cancelBtn = modal.querySelector('.btn-cancel');
        
        closeBtn.addEventListener('click', () => modal.remove());
        cancelBtn.addEventListener('click', () => modal.remove());
        
        // 产品选择变化时自动设置合适的库存阈值
        const productSelect = document.getElementById('product-select');
        productSelect.addEventListener('change', function() {
            const selectedOption = this.options[this.selectedIndex];
            if (selectedOption.value) {
                const currentStock = parseInt(selectedOption.dataset.stock);
                // 设置默认的安全库存下限为当前库存的70%，上限为130%
                document.getElementById('min-stock').value = Math.max(Math.floor(currentStock * 0.7), 5);
                document.getElementById('max-stock').value = Math.ceil(currentStock * 1.3);
            }
        });
        
        // 表单提交事件
        const form = document.getElementById('add-alert-form');
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const selectedOption = productSelect.options[productSelect.selectedIndex];
            if (!selectedOption.value) {
                showNotification('请选择商品', 'error');
                return;
            }
            
            // 获取表单数据
            const alertData = {
                product_code: selectedOption.value,
                min_stock: parseInt(document.getElementById('min-stock').value),
                max_stock: parseInt(document.getElementById('max-stock').value),
                alert_enabled: document.getElementById('alert-enabled').checked
            };
            
            // 表单验证
            if (alertData.min_stock >= alertData.max_stock) {
                showNotification('安全库存下限必须小于库存上限', 'error');
                return;
            }
            
            // 发送请求添加预警设置
            fetch('/api/inventory-alerts', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(alertData)
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    showNotification('预警设置添加成功', 'success');
                    modal.remove();
                    // 重新加载库存盘点预警模块
                    loadInventoryManagement();
                } else {
                    showNotification(data.message || '添加失败', 'error');
                }
            })
            .catch(err => {
                console.error('添加预警设置失败:', err);
                showNotification('添加预警设置失败', 'error');
            });
        });
    })
    .catch(err => {
        console.error('获取商品数据失败:', err);
        showNotification('获取商品数据失败', 'error');
    });
}

// 查看库存预警设置
function viewInventoryAlert(alertId) {
    fetch(`/api/inventory-alerts/${alertId}`)
    .then(res => res.json())
    .then(data => {
        if (!data.success) {
            throw new Error('获取预警设置数据失败');
        }
        
        const alert = data.data;
        
        // 创建模态框
        moduleContent.innerHTML += `
            <div class="modal inventory-modal" id="view-alert-modal">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3>库存预警设置详情</h3>
                        <span class="close-modal">&times;</span>
                    </div>
                    <div class="modal-body">
                        <div class="detail-section">
                            <h4>商品信息</h4>
                            <div class="detail-grid">
                                <div class="detail-item">
                                    <div class="detail-label">商品名称：</div>
                                    <div class="detail-value">${alert.product_name}</div>
                                </div>
                                <div class="detail-item">
                                    <div class="detail-label">商品编码：</div>
                                    <div class="detail-value">${alert.product_code}</div>
                                </div>
                                <div class="detail-item">
                                    <div class="detail-label">商品分类：</div>
                                    <div class="detail-value">${alert.category}</div>
                                </div>
                                <div class="detail-item">
                                    <div class="detail-label">当前库存：</div>
                                    <div class="detail-value">${alert.current_stock}</div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="detail-section">
                            <h4>预警设置</h4>
                            <div class="detail-grid">
                                <div class="detail-item">
                                    <div class="detail-label">安全库存下限：</div>
                                    <div class="detail-value">${alert.min_stock}</div>
                                </div>
                                <div class="detail-item">
                                    <div class="detail-label">库存上限：</div>
                                    <div class="detail-value">${alert.max_stock}</div>
                                </div>
                                <div class="detail-item">
                                    <div class="detail-label">预警状态：</div>
                                    <div class="detail-value">
                                        <span class="status-tag status-${alert.status === '正常' ? 'normal' : (alert.status === '预警' ? 'warning' : (alert.status === '缺货' ? 'danger' : 'overstock'))}">
                                            ${alert.status}
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="detail-section">
                            <h4>其他信息</h4>
                            <div class="detail-grid">
                                <div class="detail-item">
                                    <div class="detail-label">创建时间：</div>
                                    <div class="detail-value">${alert.create_time}</div>
                                </div>
                                <div class="detail-item">
                                    <div class="detail-label">更新时间：</div>
                                    <div class="detail-value">${alert.update_time}</div>
                                </div>
                                <div class="detail-item">
                                    <div class="detail-label">预警启用：</div>
                                    <div class="detail-value">${alert.alert_enabled ? '是' : '否'}</div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-actions">
                            <button class="btn-secondary close-btn">关闭</button>
                            <button class="btn-primary edit-btn" data-id="${alert.id}">编辑</button>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        // 显示模态框
        const modal = document.getElementById('view-alert-modal');
        modal.style.display = 'block';
        
        // 关闭按钮事件
        const closeBtn = modal.querySelector('.close-modal');
        const cancelBtn = modal.querySelector('.close-btn');
        
        closeBtn.addEventListener('click', () => modal.remove());
        cancelBtn.addEventListener('click', () => modal.remove());
        
        // 编辑按钮事件
        const editBtn = modal.querySelector('.edit-btn');
        editBtn.addEventListener('click', function() {
            modal.remove();
            editInventoryAlert(this.getAttribute('data-id'));
        });
    })
    .catch(err => {
        console.error('获取预警设置数据失败:', err);
        showNotification('获取预警设置数据失败', 'error');
    });
}

// 编辑库存预警设置
function editInventoryAlert(alertId) {
    fetch(`/api/inventory-alerts/${alertId}`)
    .then(res => res.json())
    .then(data => {
        if (!data.success) {
            throw new Error('获取预警设置数据失败');
        }
        
        const alert = data.data;
        
        // 创建模态框
        moduleContent.innerHTML += `
            <div class="modal inventory-modal" id="edit-alert-modal">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3>编辑库存预警设置</h3>
                        <span class="close-modal">&times;</span>
                    </div>
                    <div class="modal-body">
                        <form id="edit-alert-form" class="inventory-form">
                            <div class="form-group">
                                <label for="product-info">商品信息：</label>
                                <input type="text" id="product-info" class="form-control" value="${alert.product_name} (${alert.product_code})" readonly>
                            </div>
                            
                            <div class="form-group">
                                <label for="current-stock">当前库存：</label>
                                <input type="text" id="current-stock" class="form-control" value="${alert.current_stock}" readonly>
                            </div>
                            
                            <div class="form-group">
                                <label for="edit-min-stock">安全库存下限：</label>
                                <input type="number" id="edit-min-stock" class="form-control" min="0" value="${alert.min_stock}" required>
                                <span class="form-hint">当库存低于此值时将发出预警</span>
                            </div>
                            
                            <div class="form-group">
                                <label for="edit-max-stock">库存上限：</label>
                                <input type="number" id="edit-max-stock" class="form-control" min="0" value="${alert.max_stock}" required>
                                <span class="form-hint">当库存高于此值时将显示为库存积压</span>
                            </div>
                            
                            <div class="form-group">
                                <label for="edit-alert-enabled">启用预警：</label>
                                <div class="toggle-switch">
                                    <input type="checkbox" id="edit-alert-enabled" ${alert.alert_enabled ? 'checked' : ''}>
                                    <label for="edit-alert-enabled"></label>
                                </div>
                            </div>
                            
                            <div class="form-actions">
                                <button type="button" class="btn-cancel">取消</button>
                                <button type="submit" class="btn-save">保存修改</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        `;
        
        // 显示模态框
        const modal = document.getElementById('edit-alert-modal');
        modal.style.display = 'block';
        
        // 关闭模态框事件
        const closeBtn = modal.querySelector('.close-modal');
        const cancelBtn = modal.querySelector('.btn-cancel');
        
        closeBtn.addEventListener('click', () => modal.remove());
        cancelBtn.addEventListener('click', () => modal.remove());
        
        // 表单提交事件
        const form = document.getElementById('edit-alert-form');
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 获取表单数据
            const alertData = {
                min_stock: parseInt(document.getElementById('edit-min-stock').value),
                max_stock: parseInt(document.getElementById('edit-max-stock').value),
                alert_enabled: document.getElementById('edit-alert-enabled').checked
            };
            
            // 表单验证
            if (alertData.min_stock >= alertData.max_stock) {
                showNotification('安全库存下限必须小于库存上限', 'error');
                return;
            }
            
            // 发送请求更新预警设置
            fetch(`/api/inventory-alerts/${alertId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(alertData)
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    showNotification('预警设置更新成功', 'success');
                    modal.remove();
                    // 重新加载库存盘点预警模块
                    loadInventoryManagement();
                } else {
                    showNotification(data.message || '更新失败', 'error');
                }
            })
            .catch(err => {
                console.error('更新预警设置失败:', err);
                showNotification('更新预警设置失败', 'error');
            });
        });
    })
    .catch(err => {
        console.error('获取预警设置数据失败:', err);
        showNotification('获取预警设置数据失败', 'error');
    });
}

// 删除库存预警设置
function deleteInventoryAlert(alertId) {
    if (confirm('确定要删除此预警设置吗？')) {
        fetch(`/api/inventory-alerts/${alertId}`, {
            method: 'DELETE'
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                showNotification('预警设置删除成功', 'success');
                // 重新加载库存盘点预警模块
                loadInventoryManagement();
            } else {
                showNotification(data.message || '删除失败', 'error');
            }
        })
        .catch(err => {
            console.error('删除预警设置失败:', err);
            showNotification('删除预警设置失败', 'error');
        });
    }
}

// 通知函数
function showNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.innerHTML = `
        <div class="notification-content">
            <span class="notification-message">${message}</span>
            <button class="notification-close">&times;</button>
        </div>
    `;
    
    // 添加到文档
    document.body.appendChild(notification);
    
    // 添加关闭按钮事件
    const closeBtn = notification.querySelector('.notification-close');
    closeBtn.addEventListener('click', () => {
        notification.classList.add('notification-hidden');
        setTimeout(() => {
            notification.remove();
        }, 300);
    });
    
    // 自动关闭
    setTimeout(() => {
        notification.classList.add('notification-hidden');
        setTimeout(() => {
            notification.remove();
        }, 300);
    }, 5000);
    
    // 显示通知
    setTimeout(() => {
        notification.classList.add('notification-show');
    }, 10);
}

// 添加收银结算模块功能
function loadCheckoutModule() {
    // 初始化购物车和促销活动缓存
    let cart = [];
    let activePromotions = [];
    moduleContent.innerHTML = `
        <div class="module-header checkout-header">
            <h2>收银结算系统</h2>
            <p>一站式商品交易解决方案，快速完成收银流程</p>
        </div>
        
        <div class="checkout-container">
            <div class="checkout-left">
                <div class="search-product-section">
                    <div class="search-wrapper">
                        <input type="text" id="product-search" class="product-search-input" placeholder="搜索商品编号或名称...">
                        <button class="search-product-btn"><i>🔍</i></button>
                    </div>
                </div>
                
                <div class="product-list-section">
                    <div class="section-header">
                        <h3>商品列表</h3>
                        <span class="product-count">0 件商品</span>
                    </div>
                    <div class="products-wrapper">
                        <table class="product-table checkout-products-table">
                            <thead>
                                <tr>
                                    <th>商品编号</th>
                                    <th>商品名称</th>
                                    <th>单价</th>
                                    <th>库存</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody id="checkout-products">
                                <tr><td colspan="5" class="loading">加载中...</td></tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            
            <div class="checkout-right">
                <div class="cart-section">
                    <div class="section-header">
                        <h3>购物清单</h3>
                        <button id="clear-cart" class="clear-cart-btn" disabled>清空</button>
                    </div>
                    
                    <div class="member-section">
                        <div class="member-search">
                            <input type="text" id="member-phone" placeholder="输入会员手机号" class="member-phone-input">
                            <button id="search-member" class="search-member-btn">查找会员</button>
                        </div>
                        <div id="member-info" class="member-info">
                            <span>当前未绑定会员</span>
                        </div>
                    </div>
                    
                    <div class="cart-wrapper">
                        <table class="cart-table">
                            <thead>
                                <tr>
                                    <th>商品名称</th>
                                    <th>原价</th>
                                    <th>折后单价</th>
                                    <th>数量</th>
                                    <th>小计</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody id="checkout-cart">
                                <tr><td colspan="6" class="cart-empty">购物车为空</td></tr>
                            </tbody>
                        </table>
                    </div>
                    
                    <div class="cart-summary">
                        <div class="summary-row">
                            <span class="summary-label">商品总数:</span>
                            <span class="summary-value" id="item-count">0 件</span>
                        </div>
                        <div class="summary-row">
                            <span class="summary-label">原价总计:</span>
                            <span class="summary-value" id="original-total">¥0.00</span>
                        </div>
                        <div class="summary-row discount-row">
                            <span class="summary-label">优惠金额:</span>
                            <span class="summary-value" id="discount-display">¥0.00</span>
                        </div>
                        <div class="summary-row total-row">
                            <span class="summary-label">应付金额:</span>
                            <span class="summary-value total-amount" id="checkout-total">¥0.00</span>
                        </div>
                        <div class="summary-row points-row">
                            <span class="summary-label">预计积分:</span>
                            <span class="summary-value" id="expected-points">0</span>
                        </div>
                    </div>
                    
                    <div class="payment-section">
                        <div class="payment-methods">
                            <button class="payment-method-btn" data-method="cash">现金支付</button>
                            <button class="payment-method-btn" data-method="wechat">微信支付</button>
                            <button class="payment-method-btn" data-method="alipay">支付宝</button>
                            <button class="payment-method-btn" data-method="card">银行卡</button>
                        </div>
                        <button id="checkout-btn" class="checkout-btn" disabled>结算订单</button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    const prodList = document.getElementById('checkout-products');
    const cartList = document.getElementById('checkout-cart');
    const totalEl = document.getElementById('checkout-total');
    const originalTotalEl = document.getElementById('original-total');
    const itemCountEl = document.getElementById('item-count');
    const btnCheckout = document.getElementById('checkout-btn');
    const clearCartBtn = document.getElementById('clear-cart');
    const discountDisplayEl = document.getElementById('discount-display');
    const productSearchInput = document.getElementById('product-search');
    const productCountEl = document.querySelector('.product-count');
    const memberPhoneInput = document.getElementById('member-phone');
    const searchMemberBtn = document.getElementById('search-member');
    const memberInfoEl = document.getElementById('member-info');
    const expectedPointsEl = document.getElementById('expected-points');
    let selectedPaymentMethod = 'cash';
    let discountAmount = 0;
    let currentMember = null;
    
    // 为支付方式按钮添加点击事件
    document.querySelectorAll('.payment-method-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            document.querySelectorAll('.payment-method-btn').forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            selectedPaymentMethod = btn.dataset.method;
        });
    });
    
    // 默认选中现金支付
    document.querySelector('[data-method="cash"]').classList.add('active');
    
    // 会员搜索功能
    searchMemberBtn.addEventListener('click', () => {
        const phone = memberPhoneInput.value.trim();
        if (!phone) {
            showNotification('请输入会员手机号', 'warning');
            return;
        }
        
        // 查询会员信息
        fetch(`/api/members/phone/${phone}`)
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    currentMember = data.data;
                    
                    // 显示会员信息
                    memberInfoEl.innerHTML = `
                        <div class="member-card">
                            <div class="member-basic">
                                <span class="member-name">${currentMember.name}</span>
                                <span class="member-id">${currentMember.member_code}</span>
                            </div>
                            <div class="member-details">
                                <div class="member-points">
                                    <span class="points-label">积分:</span>
                                    <span class="points-value">${currentMember.points}</span>
                                </div>
                                <div class="member-level">
                                    <span class="level-label">等级:</span>
                                    <span class="level-value">${currentMember.level}</span>
                                </div>
                            </div>
                        </div>
                    `;
                    
                    showNotification('会员绑定成功', 'success');
                    // 更新预计积分
                    updateExpectedPoints();
                } else {
                    showNotification('未找到该会员', 'error');
                    currentMember = null;
                    memberInfoEl.innerHTML = '<span>当前未绑定会员</span>';
                    updateExpectedPoints();
                }
            })
            .catch(err => {
                console.error('搜索会员失败:', err);
                showNotification('搜索会员失败，请检查网络连接', 'error');
            });
    });
    
    // 更新预计积分
    function updateExpectedPoints() {
        if (!currentMember) {
            expectedPointsEl.textContent = '0';
            return;
        }
        
        // 计算应付金额（取整数部分作为积分）
        const totalAmount = parseFloat(totalEl.textContent.replace('¥', ''));
        const expectedPoints = Math.floor(totalAmount);
        expectedPointsEl.textContent = expectedPoints;
    }
    
    // 清空购物车按钮事件
    clearCartBtn.addEventListener('click', () => {
        if (confirm('确定要清空购物车吗？')) {
            cart = [];
            discountAmount = 0;
            discountDisplayEl.textContent = '0.00';
            renderCart();
        }
    });
    
    // 商品搜索功能
    productSearchInput.addEventListener('input', () => {
        const searchText = productSearchInput.value.toLowerCase().trim();
        const rows = document.querySelectorAll('#checkout-products tr:not(.no-results)');
        let visibleCount = 0;
        let hasResults = false;
        
        rows.forEach(row => {
            const code = row.querySelector('td:first-child')?.textContent.toLowerCase() || '';
            const name = row.querySelector('td:nth-child(2)')?.textContent.toLowerCase() || '';
            
            if (code.includes(searchText) || name.includes(searchText)) {
                row.style.display = '';
                hasResults = true;
                visibleCount++;
            } else {
                row.style.display = 'none';
            }
        });
        
        // 更新商品数量显示
        productCountEl.textContent = `${visibleCount} 件商品`;
        
        // 处理没有结果的情况
        const noResultsRow = document.querySelector('#checkout-products tr.no-results');
        if (!hasResults && !noResultsRow) {
            const tr = document.createElement('tr');
            tr.className = 'no-results';
            tr.innerHTML = `<td colspan="5" class="no-search-results">没有找到匹配的商品</td>`;
            prodList.appendChild(tr);
        } else if (hasResults && noResultsRow) {
            noResultsRow.remove();
        }
    });

    function renderCart() {
        cartList.innerHTML = '';
        if (!cart.length) {
            cartList.innerHTML = '<tr><td colspan="6" class="cart-empty">购物车为空</td></tr>';
            btnCheckout.disabled = true;
            clearCartBtn.disabled = true;
            discountDisplayEl.disabled = true;
        } else {
            cart.forEach((it, idx) => {
                // 计算折后单价（按小数折扣）
                let discounted = it.price;
                for (const promo of activePromotions) {
                    if (promo.category === '全部分类' || promo.category === it.category) {
                        // 折扣为小数（如0.8表示8折）
                        discounted = it.price * promo.discount;
                        break;
                    }
                }
                const sub = (discounted * it.qty).toFixed(2);
                cartList.innerHTML += `
                <tr>
                    <td>${it.name}</td>
                    <td>¥${it.price.toFixed(2)}</td>
                    <td>¥${discounted.toFixed(2)}</td>
                    <td>
                        <div class="quantity-control">
                            <button class="qty-btn qty-decrease" data-i="${idx}">-</button>
                            <span class="qty-value">${it.qty}</span>
                            <button class="qty-btn qty-increase" data-i="${idx}">+</button>
                        </div>
                    </td>
                    <td>¥${sub}</td>
                    <td><button class="btn-remove" data-i="${idx}"><i>🗑️</i></button></td>
                </tr>`;
            });
            btnCheckout.disabled = false;
            clearCartBtn.disabled = false;
            discountDisplayEl.disabled = false;
        }
        
        // 计算总额和商品数量
        const originalTotal = cart.reduce((s, it) => s + it.price * it.qty, 0);
        // 折后总额
        const discountedTotal = cart.reduce((s, it) => {
            let d = it.price;
            for (const promo of activePromotions) {
                if (promo.category === '全部分类' || promo.category === it.category) {
                    d = it.price * promo.discount;
                    break;
                }
            }
            return s + d * it.qty;
        }, 0);
        // 自动计算优惠金额
        discountAmount = originalTotal - discountedTotal;
        // 更新优惠金额显示
        discountDisplayEl.textContent = discountAmount.toFixed(2);
        // 应付金额 = 折后总额
        const finalTotal = discountedTotal;
        const itemCount = cart.reduce((s, it) => s + it.qty, 0);
        
        originalTotalEl.textContent = `¥${originalTotal.toFixed(2)}`;
        totalEl.textContent = `¥${finalTotal.toFixed(2)}`;
        itemCountEl.textContent = `${itemCount} 件`;
        
        // 更新预计积分
        updateExpectedPoints();
        
        // 设置删除按钮事件
        document.querySelectorAll('.btn-remove').forEach(b => {
            b.onclick = () => { 
                cart.splice(+b.dataset.i, 1); 
                renderCart();
                showNotification('商品已从购物车移除', 'info');
            };
        });
        
        // 设置数量增减按钮事件
        document.querySelectorAll('.qty-decrease').forEach(b => {
            b.onclick = () => {
                const idx = +b.dataset.i;
                if (cart[idx].qty > 1) {
                    cart[idx].qty--;
                    renderCart();
                }
            };
        });
        
        document.querySelectorAll('.qty-increase').forEach(b => {
            b.onclick = () => {
                const idx = +b.dataset.i;
                cart[idx].qty++;
                renderCart();
            };
        });
    }

    // 初始化渲染
    renderCart();
    
    // 加载促销活动数据
    fetch('/api/promotions')
        .then(r => r.json())
        .then(res => {
            if (!res.success) throw new Error(res.message || '加载促销活动失败');
            
            // 过滤出当前有效的促销活动
            const now = new Date();
            activePromotions = res.data.filter(promo => {
                const startDate = new Date(`${promo.start_date} ${promo.start_time}`);
                const endDate = new Date(`${promo.end_date} ${promo.end_time}`);
                return now >= startDate && now <= endDate && promo.status === '进行中';
            }).map(promo => ({
                id: promo.id,
                name: promo.name,
                category: promo.category,
                discount: promo.discount, // 直接使用小数折扣
            }));
            
            console.log('当前有效促销活动:', activePromotions);
        })
        .catch(err => {
            console.error('加载促销活动失败:', err);
            showNotification('加载促销活动失败', 'error');
        })
        .finally(() => {
            // 加载商品数据
            loadCheckoutProducts();
        });
    
    // 加载商品数据
    function loadCheckoutProducts() {
        fetch('/api/products')
            .then(r => r.json())
            .then(res => {
                if (!res.success) throw new Error(res.message || '加载失败');
                prodList.innerHTML = '';
                
                // 更新商品数量显示
                productCountEl.textContent = `${res.data.length} 件商品`;
                
                res.data.forEach(p => {
                    const stockClass = p.current_stock <= 0 ? 'out-of-stock' : 
                                      p.current_stock < 10 ? 'low-stock' : '';
                    prodList.innerHTML += `
                    <tr>
                        <td>${p.product_code}</td>
                        <td>${p.product_name}</td>
                        <td class="product-price">¥${p.price.toFixed(2)}</td>
                        <td class="product-stock ${stockClass}">${p.current_stock}</td>
                        <td>
                            <button class="add-to-cart-btn" data-code="${p.product_code}" 
                            ${p.current_stock <= 0 ? 'disabled' : ''}>
                                <i>🛒</i> 添加
                            </button>
                        </td>
                    </tr>`;
                });
                
                document.querySelectorAll('.add-to-cart-btn').forEach(b => {
                    b.onclick = () => {
                        const code = b.dataset.code;
                        const pr = res.data.find(x => x.product_code === code);
                        
                        if (pr.current_stock <= 0) {
                            showNotification('该商品已无库存', 'error');
                            return;
                        }
                        
                        const ex = cart.find(x => x.code === code);
                        if (ex) {
                            // 检查库存是否足够
                            if (ex.qty + 1 > pr.current_stock) {
                                showNotification('超出可用库存', 'warning');
                                return;
                            }
                            ex.qty++;
                        } else {
                            cart.push({ 
                                code, 
                                name: pr.product_name, 
                                price: pr.price, 
                                category: pr.category,
                                qty: 1 
                            });
                        }
                        renderCart();
                        showNotification(`已将 ${pr.product_name} 添加到购物车`, 'success');
                    };
                });
            })
            .catch(err => { 
                console.error(err); 
                prodList.innerHTML = '<tr><td colspan="5" class="error-message">加载商品失败</td></tr>';
                showNotification('加载商品失败', 'error'); 
            });
    }

    btnCheckout.onclick = () => {
        if (!cart.length) return;
        
        // 计算原价总计
        const originalTotal = cart.reduce((s, it) => s + it.price * it.qty, 0);
        // 计算折后总额
        const discountedTotal = cart.reduce((s, it) => {
            let d = it.price;
            for (const promo of activePromotions) {
                if (promo.category === '全部分类' || promo.category === it.category) {
                    d = it.price * promo.discount;
                    break;
                }
            }
            return s + d * it.qty;
        }, 0);
        
        // 显示结算确认对话框
        const dialogHTML = `
            <div class="checkout-modal">
                <div class="modal-content checkout-modal-content">
                    <div class="modal-header">
                        <h3>确认结算</h3>
                        <button class="close-modal">&times;</button>
                    </div>
                    <div class="modal-body">
                        <div class="checkout-summary">
                            <div class="summary-row">
                                <span class="summary-label">商品总数:</span>
                                <span class="summary-value">${cart.reduce((s, it) => s + it.qty, 0)} 件</span>
                            </div>
                            <div class="summary-row">
                                <span class="summary-label">原价总计:</span>
                                <span class="summary-value">¥${originalTotal.toFixed(2)}</span>
                            </div>
                            <div class="summary-row">
                                <span class="summary-label">折后总额:</span>
                                <span class="summary-value">¥${discountedTotal.toFixed(2)}</span>
                            </div>
                            <div class="summary-row total-row">
                                <span class="summary-label">应付金额:</span>
                                <span class="summary-value total-amount">¥${discountedTotal.toFixed(2)}</span>
                            </div>
                            <div class="summary-row">
                                <span class="summary-label">支付方式:</span>
                                <span class="summary-value payment-method">${
                                    selectedPaymentMethod === 'cash' ? '现金支付' : 
                                    selectedPaymentMethod === 'wechat' ? '微信支付' : 
                                    selectedPaymentMethod === 'alipay' ? '支付宝' : '银行卡'
                                }</span>
                            </div>
                        </div>
                        <div class="checkout-confirm-message">
                            <p>请确认以上信息无误后，点击"确认支付"按钮完成交易。</p>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button class="btn-cancel">取消</button>
                        <button class="btn-confirm">确认支付</button>
                    </div>
                </div>
            </div>
        `;
        
        document.body.insertAdjacentHTML('beforeend', dialogHTML);
        
        // 绑定事件
        const modal = document.querySelector('.checkout-modal');
        const closeBtn = modal.querySelector('.close-modal');
        const cancelBtn = modal.querySelector('.btn-cancel');
        const confirmBtn = modal.querySelector('.btn-confirm');
        
        function closeModal() {
            modal.classList.add('modal-closing');
            setTimeout(() => {
                modal.remove();
            }, 300);
        }
        
        closeBtn.onclick = closeModal;
        cancelBtn.onclick = closeModal;
        
        confirmBtn.onclick = () => {
            // 显示加载状态
            confirmBtn.disabled = true;
            confirmBtn.textContent = '处理中...';
            
            // 创建销售记录
            fetch('/api/sales', { 
                method: 'POST', 
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    payment_method: selectedPaymentMethod,
                    cashier: '收银员',
                    customer_name: currentMember ? currentMember.name : '',
                    customer_phone: currentMember ? currentMember.phone : ''
                })
            })
            .then(r => {
                if (!r.ok) throw new Error(`创建销售记录失败 (${r.status})`);
                return r.json();
            })
            .then(r => {
                if (!r.success) throw new Error(r.message || '创建销售记录失败');
                return r.data.sale_number;
            })
            // 添加商品到销售记录
            .then(no => {
                const addItemPromises = cart.map(it => 
                    fetch(`/api/sales/${no}/items`, { 
                        method: 'POST', 
                        headers: { 'Content-Type': 'application/json' }, 
                        body: JSON.stringify({ 
                            product_code: it.code, 
                            quantity: it.qty 
                        }) 
                    })
                    .then(r => {
                        if (!r.ok) {
                            return r.json().then(errData => {
                                throw new Error(errData.message || `添加商品失败 (${r.status})`);
                            }).catch(e => {
                                if (e instanceof SyntaxError) {
                                    throw new Error(`添加商品失败 (${r.status})`);
                                }
                                throw e;
                            });
                        }
                        return r.json();
                    })
                    .then(data => {
                        if (!data.success) throw new Error(data.message || '添加商品失败');
                        return data;
                    })
                );
                
                return Promise.all(addItemPromises).then(() => no);
            })
            // 完成结算
            .then(no => {
                return fetch(`/api/sales/${no}/checkout`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        payment_method: selectedPaymentMethod,
                        discount_amount: discountAmount,
                        cashier: '收银员',
                        customer_name: currentMember ? currentMember.name : '',
                        customer_phone: currentMember ? currentMember.phone : ''
                    })
                })
                .then(r => {
                    if (!r.ok) {
                        return r.text().then(txt => {
                            try {
                                const json = JSON.parse(txt);
                                throw new Error(json.message || `结算失败 (${r.status})`);
                            } catch (e) {
                                if (e instanceof SyntaxError) {
                                    throw new Error(`结算失败 (${r.status}): 服务器返回了无效的响应`);
                                }
                                throw e;
                            }
                        });
                    }
                    return r.json();
                });
            })
            .then(r => {
                if (!r.success) throw new Error(r.message || '结算失败');
                
                // 关闭模态窗口
                closeModal();
                
                // 显示成功消息
                showNotification('支付成功！', 'success');
                
                // 显示积分提示（如果是会员）
                if (r.data.member && r.data.earned_points) {
                    showNotification(`会员${r.data.member.name}获得${r.data.earned_points}积分！`, 'success');
                    
                    // 更新当前会员信息
                    currentMember = r.data.member;
                    
                    // 更新会员信息显示
                    memberInfoEl.innerHTML = `
                        <div class="member-card">
                            <div class="member-basic">
                                <span class="member-name">${currentMember.name}</span>
                                <span class="member-id">${currentMember.member_code}</span>
                            </div>
                            <div class="member-details">
                                <div class="member-points">
                                    <span class="points-label">积分:</span>
                                    <span class="points-value">${currentMember.points}</span>
                                </div>
                                <div class="member-level">
                                    <span class="level-label">等级:</span>
                                    <span class="level-value">${currentMember.level}</span>
                                </div>
                            </div>
                        </div>
                    `;
                }
                
                // 显示打印小票的选项
                showReceiptModal(r.data);
                
                // 清空购物车
                cart = [];
                discountAmount = 0;
                discountDisplayEl.textContent = '0.00';
                renderCart();
                
                // 更新欢迎界面的销售统计数据
                updateDashboardStats();
                
                // 如果当前正在查看销售统计模块，则刷新数据
                if (document.querySelector('.sales-statistics-container')) {
                    loadSalesStatistics();
                }
            })
            .catch(e => {
                console.error('结算过程出错:', e);
                confirmBtn.disabled = false;
                confirmBtn.textContent = '确认支付';
                showNotification(e.message || '结算失败，请重试', 'error');
            });
        };
    };
    
    // 显示小票模态窗口
    function showReceiptModal(data) {
        const saleData = data.sale;
        const items = data.items;
        
        const receiptHTML = `
            <div class="receipt-modal receipt-overlay" style="display:flex;align-items:center;justify-content:center;position:fixed;top:0;left:0;width:100vw;height:100vh;background:rgba(0,0,0,0.5);z-index:1000;">
                <div class="modal-content receipt-modal-content" style="background:#fff;padding:2rem;border-radius:1rem;width:500px;max-width:90vw;max-height:90vh;overflow-y:auto;position:relative;">
                    <div class="modal-header">
                        <h3>交易成功</h3>
                        <button class="close-modal" style="position:absolute;top:1rem;right:1rem;font-size:1.5rem;cursor:pointer;">&times;</button>
                    </div>
                    <div class="modal-body">
                        <div class="receipt">
                            <div class="receipt-header">
                                <h4>销售小票</h4>
                                <p>单号: ${saleData.sale_number}</p>
                                <p>日期: ${formatDate(saleData.sale_date)}</p>
                                <p>收银员: ${saleData.cashier}</p>
                            </div>
                            <div class="receipt-items">
                                <table>
                                    <thead>
                                        <tr>
                                            <th>商品</th>
                                            <th>单价</th>
                                            <th>数量</th>
                                            <th>小计</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        ${items.map(item => `
                                            <tr>
                                                <td>${item.product_name}</td>
                                                <td>¥${item.unit_price.toFixed(2)}</td>
                                                <td>${item.quantity}</td>
                                                <td>¥${item.subtotal.toFixed(2)}</td>
                                            </tr>
                                        `).join('')}
                                    </tbody>
                                </table>
                            </div>
                            <div class="receipt-summary">
                                <div class="receipt-row">
                                    <span>商品数量:</span>
                                    <span>${items.reduce((sum, item) => sum + item.quantity, 0)}件</span>
                                </div>
                                <div class="receipt-row">
                                    <span>商品总计:</span>
                                    <span>¥${saleData.total_amount.toFixed(2)}</span>
                                </div>
                                <div class="receipt-row">
                                    <span>优惠金额:</span>
                                    <span>¥${saleData.discount_amount.toFixed(2)}</span>
                                </div>
                                <div class="receipt-row total">
                                    <span>实付金额:</span>
                                    <span>¥${saleData.final_amount.toFixed(2)}</span>
                                </div>
                                <div class="receipt-row payment">
                                    <span>支付方式:</span>
                                    <span>${
                                        saleData.payment_method === 'cash' ? '现金支付' : 
                                        saleData.payment_method === 'wechat' ? '微信支付' : 
                                        saleData.payment_method === 'alipay' ? '支付宝' : '银行卡'
                                    }</span>
                                </div>
                            </div>
                            <div class="receipt-footer">
                                <p>感谢您的惠顾，欢迎再次光临！</p>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button class="btn-print">打印小票</button>
                        <button class="btn-close">关闭</button>
                    </div>
                </div>
            </div>
        `;
        
        document.body.insertAdjacentHTML('beforeend', receiptHTML);
        
        // 绑定事件
        const modal = document.querySelector('.receipt-modal');
        const closeBtn = modal.querySelector('.close-modal');
        const printBtn = modal.querySelector('.btn-print');
        const closeModalBtn = modal.querySelector('.btn-close');
        
        function closeModal() {
            modal.classList.add('modal-closing');
            setTimeout(() => {
                modal.remove();
            }, 300);
        }
        
        closeBtn.onclick = closeModal;
        closeModalBtn.onclick = closeModal;
        
        printBtn.onclick = () => {
            // 模拟打印功能
            printBtn.textContent = '打印中...';
            printBtn.disabled = true;
            
            setTimeout(() => {
                printBtn.textContent = '打印完成';
                showNotification('小票打印成功！', 'success');
                
                setTimeout(() => {
                    closeModal();
                }, 1500);
            }, 1500);
        };
    }
    
    // 初始化渲染
    renderCart();
    
    // 加载促销活动数据
    fetch('/api/promotions')
        .then(r => r.json())
        .then(res => {
            if (!res.success) throw new Error(res.message || '加载促销活动失败');
            
            // 过滤出当前有效的促销活动
            const now = new Date();
            activePromotions = res.data.filter(promo => {
                const startDate = new Date(`${promo.start_date} ${promo.start_time}`);
                const endDate = new Date(`${promo.end_date} ${promo.end_time}`);
                return now >= startDate && now <= endDate && promo.status === '进行中';
            }).map(promo => ({
                id: promo.id,
                name: promo.name,
                category: promo.category,
                discount: promo.discount, // 直接使用小数折扣
            }));
            
            console.log('当前有效促销活动:', activePromotions);
        })
        .catch(err => {
            console.error('加载促销活动失败:', err);
            showNotification('加载促销活动失败', 'error');
        })
        .finally(() => {
            // 加载商品数据
            loadCheckoutProducts();
        });
    
    // 加载商品数据
    function loadCheckoutProducts() {
        fetch('/api/products')
            .then(r => r.json())
            .then(res => {
                if (!res.success) throw new Error(res.message || '加载失败');
                prodList.innerHTML = '';
                
                // 更新商品数量显示
                productCountEl.textContent = `${res.data.length} 件商品`;
                
                res.data.forEach(p => {
                    const stockClass = p.current_stock <= 0 ? 'out-of-stock' : 
                                      p.current_stock < 10 ? 'low-stock' : '';
                    prodList.innerHTML += `
                    <tr>
                        <td>${p.product_code}</td>
                        <td>${p.product_name}</td>
                        <td class="product-price">¥${p.price.toFixed(2)}</td>
                        <td class="product-stock ${stockClass}">${p.current_stock}</td>
                        <td>
                            <button class="add-to-cart-btn" data-code="${p.product_code}" 
                            ${p.current_stock <= 0 ? 'disabled' : ''}>
                                <i>🛒</i> 添加
                            </button>
                        </td>
                    </tr>`;
                });
                
                document.querySelectorAll('.add-to-cart-btn').forEach(b => {
                    b.onclick = () => {
                        const code = b.dataset.code;
                        const pr = res.data.find(x => x.product_code === code);
                        
                        if (pr.current_stock <= 0) {
                            showNotification('该商品已无库存', 'error');
                            return;
                        }
                        
                        const ex = cart.find(x => x.code === code);
                        if (ex) {
                            // 检查库存是否足够
                            if (ex.qty + 1 > pr.current_stock) {
                                showNotification('超出可用库存', 'warning');
                                return;
                            }
                            ex.qty++;
                        } else {
                            cart.push({ 
                                code, 
                                name: pr.product_name, 
                                price: pr.price, 
                                category: pr.category,
                                qty: 1 
                            });
                        }
                        renderCart();
                        showNotification(`已将 ${pr.product_name} 添加到购物车`, 'success');
                    };
                });
            })
            .catch(err => { 
                console.error(err); 
                prodList.innerHTML = '<tr><td colspan="5" class="error-message">加载商品失败</td></tr>';
                showNotification('加载商品失败', 'error'); 
            });
    }
}

// 添加销售统计模块（替代原财务报表生成）
function loadSalesStatisticsModule() {
    moduleContent.innerHTML = `
        <div class="module-header">
            <h2>销售统计</h2>
            <p>查看销售数据分析和商品销售记录</p>
        </div>
        
        <div class="sales-statistics-container">
            <div class="filter-section">
                <div class="date-filter">
                    <label>日期范围：</label>
                    <input type="date" id="start-date" class="date-input">
                    <span>至</span>
                    <input type="date" id="end-date" class="date-input">
                    <button id="search-btn" class="search-btn">查询</button>
                    <button id="reset-btn" class="btn-reset">重置</button>
                </div>
            </div>
            
            <div class="statistics-cards">
                <div class="stat-card">
                    <div class="stat-icon stat-blue">
                        <i>💰</i>
                    </div>
                    <div class="stat-info">
                        <div class="stat-label">总销售额</div>
                        <div class="stat-number" id="total-sales">¥0.00</div>
                    </div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-icon stat-green">
                        <i>🛒</i>
                    </div>
                    <div class="stat-info">
                        <div class="stat-label">订单数量</div>
                        <div class="stat-number" id="order-count">0</div>
                    </div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-icon stat-orange">
                        <i>📦</i>
                    </div>
                    <div class="stat-info">
                        <div class="stat-label">商品总数</div>
                        <div class="stat-number" id="total-items">0</div>
                    </div>
                </div>
            </div>
            
            <div class="monthly-data-container">
                <div class="monthly-chart-section">
                    <h3>月度销售趋势</h3>
                    <div class="year-selector">
                        <label>选择年份：</label>
                        <select id="chart-year-select" class="year-select">
                            ${generateYearOptions()}
                        </select>
                    </div>
                    <div class="chart-title">该项目1~12月销售额</div>
                    <div class="chart-container">
                        <canvas id="monthly-sales-chart"></canvas>
                    </div>
                </div>
                
                <div class="monthly-stats-section">
                    <h3>月度销售统计</h3>
                    <div class="year-selector">
                        <label>选择年份：</label>
                        <select id="year-select" class="year-select">
                            ${generateYearOptions()}
                        </select>
                    </div>
                    <div class="table-container">
                        <table class="monthly-table">
                            <thead>
                                <tr>
                                    <th>月份</th>
                                    <th>销售额</th>
                                    <th>订单数</th>
                                    <th>商品数</th>
                                    <th>原价总额</th>
                                    <th>优惠金额</th>
                                </tr>
                            </thead>
                            <tbody id="monthly-stats">
                                <tr>
                                    <td colspan="6" class="loading">加载中...</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            
            <div class="sales-records-section">
                <h3>销售记录</h3>
                <div class="table-container">
                    <table class="sales-table">
                        <thead>
                            <tr>
                                <th>订单号</th>
                                <th>日期</th>
                                <th>商品名称</th>
                                <th>数量</th>
                                <th>单价</th>
                                <th>小计</th>
                                <th>支付方式</th>
                            </tr>
                        </thead>
                        <tbody id="sales-records">
                            <tr>
                                <td colspan="7" class="loading">加载中...</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <!-- 添加分页控件容器 -->
                <div id="sales-pagination" class="pagination-container"></div>
            </div>
        </div>
    `;
    
    // 生成年份选项的函数
    function generateYearOptions() {
        const currentYear = new Date().getFullYear();
        let options = '';
        for (let year = currentYear; year >= currentYear - 5; year--) {
            options += `<option value="${year}">${year}年</option>`;
        }
        return options;
    }
    
    // 设置默认日期范围（默认显示本月）
    const today = new Date();
    const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
    
    document.getElementById('start-date').value = formatDateForInput(firstDay);
    document.getElementById('end-date').value = formatDateForInput(today);
    
    // 加载销售统计数据
    loadSalesStatistics();
    
    // 加载月度销售统计数据
    loadMonthlySalesStats();
    
    // 添加事件监听
    document.getElementById('search-btn').addEventListener('click', loadSalesStatistics);
    document.getElementById('reset-btn').addEventListener('click', () => {
        document.getElementById('start-date').value = formatDateForInput(firstDay);
        document.getElementById('end-date').value = formatDateForInput(today);
        loadSalesStatistics();
    });
    
    document.getElementById('year-select').addEventListener('change', loadMonthlySalesStats);
    document.getElementById('chart-year-select').addEventListener('change', loadMonthlyChart);
    
    // 初始加载月度销售图表
    loadMonthlyChart();
}

// 加载月度销售统计图表
function loadMonthlyChart() {
    const yearSelect = document.getElementById('chart-year-select');
    const year = yearSelect ? yearSelect.value : new Date().getFullYear();
    
    const chartCanvas = document.getElementById('monthly-sales-chart');
    if (!chartCanvas) return;
    
    // 更新图表标题
    const chartTitle = document.querySelector('.chart-title');
    if (chartTitle) {
        chartTitle.textContent = `${year}年1~12月销售额`;
    }
    
    // 获取月度销售统计数据
    fetch(`/api/sales/monthly-stats?year=${year}`)
        .then(res => res.json())
        .then(response => {
            if (!response.success) {
                throw new Error(response.message || '获取月度销售统计数据失败');
            }
            
            const data = response.data;
            
            // 准备图表数据
            const months = Array(12).fill(0).map((_, i) => i + 1); // 1到12月
            const salesData = Array(12).fill(0);
            
            // 填充销售数据（如果有）
            if (data.length > 0) {
                data.forEach(monthData => {
                    const monthIndex = parseInt(monthData.month.split('-')[1]) - 1;
                    salesData[monthIndex] = parseFloat(monthData.total_amount);
                });
            }
            
            // 销毁已存在的图表实例
            if (window.salesChart) {
                window.salesChart.destroy();
            }
            
            // 创建图表
            window.salesChart = new Chart(chartCanvas, {
                type: 'line',
                data: {
                    labels: months.map(m => `${m}月`),
                    datasets: [{
                        label: '月度销售额',
                        data: salesData,
                        borderColor: '#e83e8c',
                        backgroundColor: 'rgba(232, 62, 140, 0.05)',
                        borderWidth: 2.5,
                        tension: 0.4,
                        fill: true,
                        pointBackgroundColor: '#fff',
                        pointBorderColor: '#e83e8c',
                        pointBorderWidth: 2,
                        pointRadius: 5,
                        pointHoverRadius: 7,
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            grid: {
                                color: 'rgba(0, 0, 0, 0.05)'
                            },
                            ticks: {
                                font: {
                                    size: 11
                                }
                            }
                        },
                        x: {
                            grid: {
                                display: false
                            },
                            ticks: {
                                font: {
                                    size: 11
                                }
                            }
                        }
                    },
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    return `销售额: ¥${context.raw.toFixed(2)}`;
                                }
                            }
                        },
                        datalabels: {
                            align: 'top',
                            anchor: 'end',
                            color: '#333',
                            font: {
                                weight: 'bold',
                                size: 11
                            },
                            formatter: function(value) {
                                return value > 0 ? '¥' + value.toFixed(2) : '';
                            },
                            display: function(context) {
                                return context.dataset.data[context.dataIndex] > 0;
                            }
                        }
                    },
                    elements: {
                        line: {
                            tension: 0.4
                        }
                    }
                },
                plugins: [{
                    afterDraw: function(chart) {
                        const ctx = chart.ctx;
                        ctx.save();
                        
                        const dataSet = chart.data.datasets[0].data;
                        const meta = chart.getDatasetMeta(0);
                        
                        // 检查是否所有的数据都是0
                        const allZeros = dataSet.every(value => value === 0);
                        
                        if (allZeros) {
                            // 如果所有数据都是0，显示提示信息
                            const width = chart.width;
                            const height = chart.height;
                            ctx.fillStyle = 'rgba(150, 150, 150, 0.7)';
                            ctx.textAlign = 'center';
                            ctx.textBaseline = 'middle';
                            ctx.font = 'bold 14px Arial';
                            ctx.fillText(`${year}年暂无销售数据`, width / 2, height / 2);
                        } else {
                            // 否则显示数据点的值
                            dataSet.forEach((value, index) => {
                                if (value > 0) {
                                    const point = meta.data[index];
                                    ctx.fillStyle = '#333';
                                    ctx.textAlign = 'center';
                                    ctx.textBaseline = 'bottom';
                                    ctx.font = 'bold 11px Arial';
                                    ctx.fillText(value.toFixed(2), point.x, point.y - 10);
                                }
                            });
                        }
                        
                        ctx.restore();
                    }
                }]
            });
        })
        .catch(err => {
            console.error('加载月度销售统计图表失败:', err);
            
            // 在出错时创建一个空图表
            if (window.salesChart) {
                window.salesChart.destroy();
            }
            
            const months = Array(12).fill(0).map((_, i) => i + 1);
            const salesData = Array(12).fill(0);
            
            window.salesChart = new Chart(chartCanvas, {
                type: 'line',
                data: {
                    labels: months.map(m => `${m}月`),
                    datasets: [{
                        label: '月度销售额',
                        data: salesData,
                        borderColor: '#e83e8c',
                        backgroundColor: 'rgba(232, 62, 140, 0.05)',
                        borderWidth: 2.5,
                        tension: 0.4,
                        fill: true,
                        pointBackgroundColor: '#fff',
                        pointBorderColor: '#e83e8c',
                        pointBorderWidth: 2,
                        pointRadius: 5,
                        pointHoverRadius: 7,
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                },
                plugins: [{
                    afterDraw: function(chart) {
                        const ctx = chart.ctx;
                        ctx.save();
                        const width = chart.width;
                        const height = chart.height;
                        ctx.fillStyle = 'rgba(150, 150, 150, 0.7)';
                        ctx.textAlign = 'center';
                        ctx.textBaseline = 'middle';
                        ctx.font = 'bold 14px Arial';
                        ctx.fillText(`加载图表失败: ${err.message}`, width / 2, height / 2);
                        ctx.restore();
                    }
                }]
            });
        });
}

// 加载月度销售统计数据
function loadMonthlySalesStats() {
    const yearSelect = document.getElementById('year-select');
    const year = yearSelect ? yearSelect.value : new Date().getFullYear();
    
    const monthlyStatsElement = document.getElementById('monthly-stats');
    if (!monthlyStatsElement) return;
    
    // 显示加载状态
    monthlyStatsElement.innerHTML = '<tr><td colspan="6" class="loading">加载中...</td></tr>';
    
    // 获取月度销售统计数据
    fetch(`/api/sales/monthly-stats?year=${year}`)
        .then(res => res.json())
        .then(response => {
            if (!response.success) {
                throw new Error(response.message || '获取月度销售统计数据失败');
            }
            
            const data = response.data;
            
            if (data.length === 0) {
                monthlyStatsElement.innerHTML = '<tr><td colspan="6" class="empty">暂无销售数据</td></tr>';
                return;
            }
            
            // 确保数据按月份排序
            data.sort((a, b) => {
                const monthA = parseInt(a.month.split('-')[1]);
                const monthB = parseInt(b.month.split('-')[1]);
                return monthA - monthB;
            });
            
            // 更新月度统计表格
            let html = '';
            data.forEach(month => {
                const monthName = month.month.split('-')[1] + '月';
                html += `
                    <tr>
                        <td>${monthName}</td>
                        <td>¥${parseFloat(month.total_amount).toFixed(2)}</td>
                        <td>${month.order_count}</td>
                        <td>${month.item_count}</td>
                        <td>¥${parseFloat(month.original_amount).toFixed(2)}</td>
                        <td>¥${parseFloat(month.discount_amount).toFixed(2)}</td>
                    </tr>
                `;
            });
            
            // 添加合计行
            const totalAmount = data.reduce((sum, month) => sum + parseFloat(month.total_amount || 0), 0);
            const totalOrders = data.reduce((sum, month) => sum + parseInt(month.order_count || 0), 0);
            const totalItems = data.reduce((sum, month) => sum + parseInt(month.item_count || 0), 0);
            const totalOriginal = data.reduce((sum, month) => sum + parseFloat(month.original_amount || 0), 0);
            const totalDiscount = data.reduce((sum, month) => sum + parseFloat(month.discount_amount || 0), 0);
            
            html += `
                <tr class="total-row">
                    <td>合计</td>
                    <td>¥${totalAmount.toFixed(2)}</td>
                    <td>${totalOrders}</td>
                    <td>${totalItems}</td>
                    <td>¥${totalOriginal.toFixed(2)}</td>
                    <td>¥${totalDiscount.toFixed(2)}</td>
                </tr>
            `;
            
            monthlyStatsElement.innerHTML = html;
            
            // 更新标题显示年份
            const titleElement = document.querySelector('.monthly-stats-section h3');
            if (titleElement) {
                titleElement.textContent = `${year}年度销售统计`;
            }
        })
        .catch(err => {
            console.error('加载月度销售统计数据失败:', err);
            monthlyStatsElement.innerHTML = `
                <tr>
                    <td colspan="6" class="error">加载月度销售统计数据失败: ${err.message}</td>
                </tr>
            `;
        });
}

// 添加一个函数来更新主界面的销售统计数据
function updateDashboardStats() {
    // 获取当前日期
    const today = new Date();
    const todayStr = formatDateForInput(today);
    
    // 获取今日销售统计数据
    fetch(`/api/sales/stats?start_date=${todayStr}&end_date=${todayStr}`)
        .then(res => res.json())
        .then(response => {
            if (!response.success) {
                console.error('获取销售统计数据失败:', response.message);
                return;
            }
            
            const data = response.data;
            
            // 更新欢迎界面上的销售统计数据（如果存在）
            const todaySales = document.getElementById('today-sales');
            const pendingOrders = document.getElementById('pending-orders');
            const soldItems = document.getElementById('sold-items');
            
            if (todaySales) {
                todaySales.textContent = `¥${data.total_sales.toFixed(2)}`;
            }
            
            if (pendingOrders) {
                pendingOrders.textContent = data.order_count;
            }
            
            if (soldItems) {
                soldItems.textContent = data.total_items || '0';
            }
        })
        .catch(err => {
            console.error('更新销售统计数据失败:', err);
        });
}

// 添加销售统计数据加载函数
function loadSalesStatistics() {
    // 获取日期范围
    const startDate = document.getElementById('start-date').value;
    const endDate = document.getElementById('end-date').value;
    
    // 调用API获取销售统计数据
    fetch(`/api/sales/stats?start_date=${startDate}&end_date=${endDate}`)
        .then(res => res.json())
        .then(response => {
            if (!response.success) {
                throw new Error(response.message || '获取销售统计数据失败');
            }
            
            const data = response.data;
            
            // 更新销售统计卡片
            document.getElementById('total-sales').textContent = `¥${data.total_sales.toFixed(2)}`;
            document.getElementById('order-count').textContent = data.order_count;
            document.getElementById('total-items').textContent = data.total_items || '0';
            
            // 加载销售记录
            loadSalesRecords(startDate, endDate);
        })
        .catch(err => {
            console.error('加载销售统计数据失败:', err);
            showNotification(`加载销售统计数据失败: ${err.message}`, 'error');
        });
}

// 添加销售记录加载函数
function loadSalesRecords(startDate, endDate, page = 1) {
    const salesRecordsTable = document.getElementById('sales-records');
    const paginationContainer = document.getElementById('sales-pagination');
    if (!salesRecordsTable) return;
    
    // 显示加载状态
    salesRecordsTable.innerHTML = '<tr><td colspan="7" class="loading">加载中...</td></tr>';
    
    // 调用API获取销售记录
    fetch(`/api/sales/records?start_date=${startDate}&end_date=${endDate}`)
        .then(res => res.json())
        .then(response => {
            if (!response.success) {
                throw new Error(response.message || '获取销售记录失败');
            }
            
            const sales = response.data;
            
            if (sales.length === 0) {
                salesRecordsTable.innerHTML = '<tr><td colspan="7" class="empty">暂无销售记录</td></tr>';
                if (paginationContainer) {
                    paginationContainer.innerHTML = '';
                }
                return;
            }
            
            // 构建扁平化的销售记录列表
            let flattenedSales = [];
            sales.forEach(sale => {
                const items = sale.items || [];
                items.forEach((item, index) => {
                    flattenedSales.push({
                        saleNumber: index === 0 ? sale.sale_number : '',
                        saleDate: index === 0 ? sale.sale_date : '',
                        productName: item.product_name,
                        quantity: item.quantity,
                        unitPrice: item.unit_price,
                        subtotal: item.subtotal,
                        paymentMethod: index === 0 ? sale.payment_method : ''
                    });
                });
            });
            
            // 分页逻辑
            const pageSize = 10; // 每页显示10条
            const totalPages = Math.ceil(flattenedSales.length / pageSize);
            const currentPage = Math.min(Math.max(1, page), totalPages);
            
            // 切片当前页的数据
            const startIndex = (currentPage - 1) * pageSize;
            const endIndex = Math.min(startIndex + pageSize, flattenedSales.length);
            const currentPageData = flattenedSales.slice(startIndex, endIndex);
            
            // 更新销售记录表格
            let html = '';
            currentPageData.forEach(item => {
                html += `
                    <tr>
                        <td>${item.saleNumber}</td>
                        <td>${item.saleDate}</td>
                        <td>${item.productName}</td>
                        <td>${item.quantity}</td>
                        <td>¥${parseFloat(item.unitPrice).toFixed(2)}</td>
                        <td>¥${parseFloat(item.subtotal).toFixed(2)}</td>
                        <td>${item.paymentMethod}</td>
                    </tr>
                `;
            });
            
            salesRecordsTable.innerHTML = html;
            
            // 更新分页控件
            if (paginationContainer) {
                updatePagination(paginationContainer, currentPage, totalPages, startDate, endDate);
            }
        })
        .catch(err => {
            console.error('加载销售记录失败:', err);
            salesRecordsTable.innerHTML = `
                <tr>
                    <td colspan="7" class="error">加载销售记录失败: ${err.message}</td>
                </tr>
            `;
            if (paginationContainer) {
                paginationContainer.innerHTML = '';
            }
        });
}

// 更新分页控件
function updatePagination(container, currentPage, totalPages, startDate, endDate) {
    if (totalPages <= 1) {
        container.innerHTML = '';
        return;
    }
    
    let html = '<div class="pagination">';
    
    // 上一页按钮
    html += `
        <button class="pagination-btn ${currentPage === 1 ? 'disabled' : ''}" 
            ${currentPage === 1 ? 'disabled' : `onclick="loadSalesRecords('${startDate}', '${endDate}', ${currentPage - 1})"`}>
            上一页
        </button>
    `;
    
    // 页码按钮
    const maxVisiblePages = 5;
    let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
    let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);
    
    if (endPage - startPage + 1 < maxVisiblePages) {
        startPage = Math.max(1, endPage - maxVisiblePages + 1);
    }
    
    if (startPage > 1) {
        html += `
            <button class="pagination-btn" onclick="loadSalesRecords('${startDate}', '${endDate}', 1)">1</button>
            ${startPage > 2 ? '<span class="pagination-ellipsis">...</span>' : ''}
        `;
    }
    
    for (let i = startPage; i <= endPage; i++) {
        html += `
            <button class="pagination-btn ${i === currentPage ? 'active' : ''}" 
                onclick="loadSalesRecords('${startDate}', '${endDate}', ${i})">
                ${i}
            </button>
        `;
    }
    
    if (endPage < totalPages) {
        html += `
            ${endPage < totalPages - 1 ? '<span class="pagination-ellipsis">...</span>' : ''}
            <button class="pagination-btn" onclick="loadSalesRecords('${startDate}', '${endDate}', ${totalPages})">
                ${totalPages}
            </button>
        `;
    }
    
    // 下一页按钮
    html += `
        <button class="pagination-btn ${currentPage === totalPages ? 'disabled' : ''}"
            ${currentPage === totalPages ? 'disabled' : `onclick="loadSalesRecords('${startDate}', '${endDate}', ${currentPage + 1})"`}>
            下一页
        </button>
    `;
    
    // 页码信息
    html += `
        <span class="pagination-info">第 ${currentPage}/${totalPages} 页，共 ${totalPages} 页</span>
    `;
    
    html += '</div>';
    container.innerHTML = html;
}

// 添加成本核算模块
function loadCostModule() {
    moduleContent.innerHTML = `
        <div class="module-header">
            <h2>成本核算</h2>
            <p>查看各批次商品入库成本及总成本统计</p>
        </div>
        
        <div class="cost-analysis-container">
            <div class="filter-section">
                <div class="search-bar">
                    <input type="date" id="start-date" class="search-input" placeholder="开始日期">
                    <span>至</span>
                    <input type="date" id="end-date" class="search-input" placeholder="结束日期">
                    
                    <select id="product-filter" class="search-select">
                        <option value="">所有商品</option>
                    </select>
                    
                    <button id="search-btn" class="search-btn">查询</button>
                    <button id="reset-btn" class="btn-reset">重置</button>
                </div>
            </div>
            
            <div class="statistics-cards cost-cards">
                <div class="stat-card">
                    <div class="stat-icon stat-blue">
                        <i>🛒</i>
                    </div>
                    <div class="stat-info">
                        <div class="stat-label">商品批次总数</div>
                        <div class="stat-number" id="batch-count">0</div>
                    </div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-icon stat-orange">
                        <i>📦</i>
                    </div>
                    <div class="stat-info">
                        <div class="stat-label">入库商品总数</div>
                        <div class="stat-number" id="total-quantity">0</div>
                    </div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-icon stat-green">
                        <i>💰</i>
                    </div>
                    <div class="stat-info">
                        <div class="stat-label">总成本</div>
                        <div class="stat-number" id="total-cost">¥0.00</div>
                    </div>
                </div>
            </div>
            
            <div class="product-list-container">
                <div class="table-container">
                    <table class="product-table cost-table">
                        <thead>
                            <tr>
                                <th>入库日期</th>
                                <th>入库单号</th>
                                <th>商品编码</th>
                                <th>商品名称</th>
                                <th>批次号</th>
                                <th class="text-right">入库数量</th>
                                <th class="text-right">单件成本 (¥)</th>
                                <th class="text-right">批次总成本 (¥)</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="cost-list">
                            <tr>
                                <td colspan="9" class="loading">加载中...</td>
                            </tr>
                        </tbody>
                        <tfoot id="cost-summary">
                            <tr>
                                <td colspan="5" class="text-right"><strong>总计：</strong></td>
                                <td class="text-right" id="footer-total-quantity">0</td>
                                <td class="text-right">-</td>
                                <td class="text-right" id="footer-total-cost">¥0.00</td>
                                <td></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
                <div id="cost-pagination" class="pagination-container"></div>
            </div>
        </div>
    `;
    
    // 设置默认日期范围：当前月份
    const today = new Date();
    const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
    const lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0);
    
    document.getElementById('start-date').value = formatDate(firstDay);
    document.getElementById('end-date').value = formatDate(lastDay);
    
    // 加载商品下拉选项
    fetch('/api/products')
        .then(res => res.json())
        .then(productsResponse => {
            if (productsResponse.success) {
                const productFilter = document.getElementById('product-filter');
                productsResponse.data.forEach(product => {
                    const option = document.createElement('option');
                    option.value = product.product_code;
                    option.textContent = product.product_name;
                    productFilter.appendChild(option);
                });
            }
        })
        .catch(err => {
            console.error('加载商品数据失败:', err);
        });
    
    // 加载成本数据
    loadCostData();
    
    // 添加搜索和重置按钮事件
    document.getElementById('search-btn').addEventListener('click', function() {
        loadCostData();
    });
    
    document.getElementById('reset-btn').addEventListener('click', function() {
        document.getElementById('start-date').value = formatDate(firstDay);
        document.getElementById('end-date').value = formatDate(lastDay);
        document.getElementById('product-filter').value = '';
        loadCostData();
    });
}

// 加载成本数据
function loadCostData(page = 1) {
    const startDate = document.getElementById('start-date').value;
    const endDate = document.getElementById('end-date').value;
    const productCode = document.getElementById('product-filter').value;
    
    // 构建查询参数
    let queryParams = [];
    if (startDate) queryParams.push(`start_date=${startDate}`);
    if (endDate) queryParams.push(`end_date=${endDate}`);
    if (productCode) queryParams.push(`product_code=${productCode}`);
    
    fetch(`/api/stock-in-records?${queryParams.join('&')}`)
        .then(res => res.json())
        .then(response => {
            if (!response.success) {
                throw new Error(response.message || '获取数据失败');
            }
            // 解析数据：后端返回的是数组
            const rawData = response.data;
            const allRecords = Array.isArray(rawData) ? rawData : (rawData.records || []);
            const totalRecords = allRecords.length;
            
            // 添加分页逻辑
            const pageSize = 10; // 每页显示10条记录
            const totalPages = Math.ceil(totalRecords / pageSize);
            
            // 确保页码有效
            const validPage = Math.max(1, Math.min(page, totalPages || 1));
            
            // 计算当前页的记录
            const startIndex = (validPage - 1) * pageSize;
            const endIndex = Math.min(startIndex + pageSize, totalRecords);
            const records = allRecords.slice(startIndex, endIndex);
            
            // 计算统计信息 (基于所有记录，而不只是当前页)
            let totalQuantity = 0;
            let totalCost = 0;
            
            allRecords.forEach(record => {
                const cost = parseFloat(record.operator) || 0;
                const quantity = parseInt(record.quantity) || 0;
                totalQuantity += quantity;
                totalCost += cost * quantity;
            });
            
            // 渲染表格
            const costList = document.getElementById('cost-list');
            
            if (records.length === 0) {
                costList.innerHTML = '<tr><td colspan="9" class="no-data">暂无数据</td></tr>';
                updateCostStatistics(0, 0, 0);
                document.getElementById('footer-total-quantity').textContent = '0';
                document.getElementById('footer-total-cost').textContent = '¥0.00';
                createCostPagination(
                    document.getElementById('cost-pagination'), 
                    validPage, 
                    totalPages, 
                    (pageNum) => loadCostData(pageNum, startDate, endDate, productCode)
                );
                return;
            }
            
            costList.innerHTML = records.map((record, index) => {
                // 计算批次总成本（单件成本 * 数量）
                const cost = parseFloat(record.operator) || 0; // operator字段存储的是商品成本
                const quantity = parseInt(record.quantity) || 0;
                const batchTotalCost = cost * quantity;
                
                return `
                    <tr ${index % 2 === 0 ? 'class="even-row"' : ''}>
                        <td>${record.entry_date}</td>
                        <td>${record.record_number}</td>
                        <td>${record.product_code}</td>
                        <td>${record.product_name}</td>
                        <td>${record.batch_number || '无批次号'}</td>
                        <td class="text-right">${quantity.toLocaleString()}</td>
                        <td class="text-right">${cost.toFixed(2)}</td>
                        <td class="text-right">${batchTotalCost.toFixed(2)}</td>
                        <td>
                            <button class="action-btn view-btn" data-record="${record.record_number}" title="查看详情">
                                <i>👁️</i>
                            </button>
                        </td>
                    </tr>
                `;
            }).join('');
            
            // 添加查看详情点击事件
            document.querySelectorAll('#cost-list .view-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const recordNumber = this.dataset.record;
                    viewStockInRecord(recordNumber);
                });
            });
            
            // 更新统计信息
            updateCostStatistics(allRecords.length, totalQuantity, totalCost);
            
            // 更新表格底部的总计
            document.getElementById('footer-total-quantity').textContent = totalQuantity.toLocaleString();
            document.getElementById('footer-total-cost').textContent = `¥${totalCost.toFixed(2)}`;
            
            // 更新分页
            createCostPagination(
                document.getElementById('cost-pagination'), 
                validPage, 
                totalPages, 
                (pageNum) => loadCostData(pageNum, startDate, endDate, productCode)
            );
        })
        .catch(err => {
            console.error('获取成本数据失败:', err);
            document.getElementById('cost-list').innerHTML = `
                <tr>
                    <td colspan="9" class="error-message">
                        获取数据失败：${err.message}
                    </td>
                </tr>
            `;
            updateCostStatistics(0, 0, 0);
            document.getElementById('footer-total-quantity').textContent = '0';
            document.getElementById('footer-total-cost').textContent = '¥0.00';
            
            // 清空分页
            document.getElementById('cost-pagination').innerHTML = '';
        });
}

// 更新成本统计信息
function updateCostStatistics(batchCount, totalQuantity, totalCost) {
    document.getElementById('batch-count').textContent = batchCount;
    document.getElementById('total-quantity').textContent = totalQuantity;
    document.getElementById('total-cost').textContent = `¥${totalCost.toFixed(2)}`;
}

// 为成本核算模块更新分页
function updateCostPagination(container, currentPage, totalPages, startDate, endDate, productCode) {
    if (!container) return;
    
    if (totalPages <= 1) {
        container.innerHTML = '';
        return;
    }
    
    // 计算显示的页码范围
    const pageRange = 5;
    let startPage = Math.max(1, currentPage - Math.floor(pageRange / 2));
    let endPage = Math.min(totalPages, startPage + pageRange - 1);
    
    if (endPage - startPage + 1 < pageRange) {
        startPage = Math.max(1, endPage - pageRange + 1);
    }
    
    // 生成分页HTML
    let paginationHTML = '';
    
    // 添加"上一页"按钮
    if (currentPage > 1) {
        paginationHTML += `<button class="page-btn prev-page" data-page="${currentPage - 1}">上一页</button>`;
    } else {
        paginationHTML += `<button class="page-btn prev-page disabled">上一页</button>`;
    }
    
    // 添加页码按钮
    for (let i = startPage; i <= endPage; i++) {
        if (i === currentPage) {
            paginationHTML += `<button class="page-btn page-number active" data-page="${i}">${i}</button>`;
        } else {
            paginationHTML += `<button class="page-btn page-number" data-page="${i}">${i}</button>`;
        }
    }
    
    // 添加"下一页"按钮
    if (currentPage < totalPages) {
        paginationHTML += `<button class="page-btn next-page" data-page="${currentPage + 1}">下一页</button>`;
    } else {
        paginationHTML += `<button class="page-btn next-page disabled">下一页</button>`;
    }
    
    // 添加页码信息
    paginationHTML += `<span class="pagination-info">第 ${currentPage}/${totalPages} 页</span>`;
    
    // 填充HTML并添加事件监听
    container.innerHTML = paginationHTML;
    
    // 添加点击事件
    container.querySelectorAll('.page-btn:not(.disabled)').forEach(btn => {
        btn.addEventListener('click', function() {
            const page = parseInt(this.dataset.page);
            loadCostData(page, startDate, endDate, productCode);
        });
    });
}

// 为成本核算创建简单分页函数
function createCostPagination(container, currentPage, totalPages, callback) {
    if (!container) return;
    
    if (totalPages <= 1) {
        container.innerHTML = '';
        return;
    }
    
    // 计算显示的页码范围
    const pageRange = 5;
    let startPage = Math.max(1, currentPage - Math.floor(pageRange / 2));
    let endPage = Math.min(totalPages, startPage + pageRange - 1);
    
    if (endPage - startPage + 1 < pageRange) {
        startPage = Math.max(1, endPage - pageRange + 1);
    }
    
    // 生成分页HTML
    let paginationHTML = '<div class="pagination">';
    
    // 添加"上一页"按钮
    if (currentPage > 1) {
        paginationHTML += `<button class="pagination-btn" data-page="${currentPage - 1}">上一页</button>`;
    } else {
        paginationHTML += `<button class="pagination-btn disabled">上一页</button>`;
    }
    
    // 添加页码按钮
    for (let i = startPage; i <= endPage; i++) {
        if (i === currentPage) {
            paginationHTML += `<button class="pagination-btn active" data-page="${i}">${i}</button>`;
        } else {
            paginationHTML += `<button class="pagination-btn" data-page="${i}">${i}</button>`;
        }
    }
    
    // 添加"下一页"按钮
    if (currentPage < totalPages) {
        paginationHTML += `<button class="pagination-btn" data-page="${currentPage + 1}">下一页</button>`;
    } else {
        paginationHTML += `<button class="pagination-btn disabled">下一页</button>`;
    }
    
    // 页码信息
    paginationHTML += `<span class="pagination-info">第 ${currentPage}/${totalPages} 页</span>`;
    paginationHTML += '</div>';
    
    // 填充HTML
    container.innerHTML = paginationHTML;
    
    // 添加点击事件
    container.querySelectorAll('.pagination-btn:not(.disabled)').forEach(btn => {
        btn.addEventListener('click', function() {
            const page = parseInt(this.dataset.page);
            if (typeof callback === 'function') {
                callback(page);
            }
        });
    });
}

// 添加税务管理模块
function loadTaxModule() {
    moduleContent.innerHTML = `
        <div class="module-header">
            <h2>税务管理</h2>
            <p>根据销售总额计算应缴税款</p>
        </div>
        <div class="tax-analysis-container">
            <div class="filter-section">
                <div class="search-bar">
                    <input type="date" id="tax-start-date" class="search-input" placeholder="开始日期">
                    <span>至</span>
                    <input type="date" id="tax-end-date" class="search-input" placeholder="结束日期">
                    <input type="number" id="tax-rate" class="search-input" placeholder="税率(如0.1)" min="0" max="1" step="0.01" value="0.10">
                    <select id="tax-payment-method" class="search-select">
                        <option value="">全部支付方式</option>
                    </select>
                    <button id="tax-search-btn" class="search-btn">查询</button>
                    <button id="tax-reset-btn" class="btn-reset">重置</button>
                    <button id="tax-export-btn" class="btn-export">导出CSV</button>
                </div>
            </div>
            <div class="statistics-cards tax-cards">
                <div class="stat-card">
                    <div class="stat-icon stat-blue"><i>💰</i></div>
                    <div class="stat-info">
                        <div class="stat-label">总销售额</div>
                        <div class="stat-number" id="tax-total-sales">¥0.00</div>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon stat-orange"><i>📊</i></div>
                    <div class="stat-info">
                        <div class="stat-label">税率</div>
                        <div class="stat-number" id="tax-rate-display">10%</div>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon stat-red"><i>💸</i></div>
                    <div class="stat-info">
                        <div class="stat-label">应缴税额</div>
                        <div class="stat-number" id="tax-amount">¥0.00</div>
                    </div>
                </div>
            </div>
            <div class="product-list-container">
                <div class="table-container">
                    <table class="product-table tax-table">
                        <thead>
                            <tr>
                                <th>订单号</th>
                                <th>日期</th>
                                <th>商品名称</th>
                                <th>数量</th>
                                <th>单价</th>
                                <th>小计</th>
                                <th>税额</th>
                                <th>支付方式</th>
                            </tr>
                        </thead>
                        <tbody id="tax-list">
                            <tr><td colspan="8" class="loading">加载中...</td></tr>
                        </tbody>
                    </table>
                </div>
                <div id="tax-pagination" class="pagination-container"></div>
            </div>
        </div>
    `;
    // 默认日期为当月
    const today = new Date();
    const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
    const lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0);
    document.getElementById('tax-start-date').value = formatDate(firstDay);
    document.getElementById('tax-end-date').value = formatDate(lastDay);
    
    document.getElementById('tax-search-btn').addEventListener('click', () => loadTaxData(1));
    document.getElementById('tax-reset-btn').addEventListener('click', () => {
        document.getElementById('tax-start-date').value = formatDate(firstDay);
        document.getElementById('tax-end-date').value = formatDate(lastDay);
        document.getElementById('tax-rate').value = '0.10';
        document.getElementById('tax-rate-display').textContent = '10%';
        loadTaxData(1);
    });
    document.getElementById('tax-export-btn').addEventListener('click', exportTaxData);
    document.getElementById('tax-payment-method').addEventListener('change', () => loadTaxData(1));
    loadTaxData(1);
}

// 加载税务数据（带分页）
function loadTaxData(page = 1) {
    const startDate = document.getElementById('tax-start-date').value;
    const endDate = document.getElementById('tax-end-date').value;
    const rate = parseFloat(document.getElementById('tax-rate').value) || 0;
    document.getElementById('tax-rate-display').textContent = (rate * 100).toFixed(0) + '%';
    
    // 获取选择的支付方式
    const paymentMethod = document.getElementById('tax-payment-method').value;
    // 构建查询URL，添加分页参数
    let url = `/api/sales/records?start_date=${startDate}&end_date=${endDate}&page=${page}&page_size=10`;
    if (paymentMethod) url += `&payment_method=${paymentMethod}`;
    
    // 显示加载中状态
    document.getElementById('tax-list').innerHTML = '<tr><td colspan="8" class="loading">加载中...</td></tr>';
    
    // 获取销售记录
    fetch(url)
        .then(res => res.json())
        .then(response => {
            if (!response.success) throw new Error(response.message || '获取数据失败');
            
            const sales = response.data;
            
            // 计算订单总金额用于统计
            const totalOrderAmount = sales.reduce((sum, sale) => sum + parseFloat(sale.final_amount || 0), 0);
            const taxAmount = totalOrderAmount * rate;
            
            // 更新统计
            document.getElementById('tax-total-sales').textContent = `¥${totalOrderAmount.toFixed(2)}`;
            document.getElementById('tax-amount').textContent = `¥${taxAmount.toFixed(2)}`;
            
            // 渲染表格
            const list = document.getElementById('tax-list');
            if (!sales.length) {
                list.innerHTML = '<tr><td colspan="8" class="no-data">暂无数据</td></tr>';
                document.getElementById('tax-pagination').innerHTML = '';
                return;
            }
            
            // 只展示每个订单的汇总信息，不展开商品明细
            let html = '';
            sales.forEach(sale => {
                // 计算订单总税额
                const orderTax = parseFloat(sale.final_amount || 0) * rate;
                const totalQuantity = (sale.items || []).reduce((sum, item) => sum + (parseInt(item.quantity) || 0), 0);
                
                html += `
                <tr>
                    <td>${sale.sale_number || ''}</td>
                    <td>${sale.sale_date || ''}</td>
                    <td>订单商品 (${(sale.items || []).length}种)</td>
                    <td>${totalQuantity}</td>
                    <td>-</td>
                    <td>¥${parseFloat(sale.final_amount || 0).toFixed(2)}</td>
                    <td>¥${orderTax.toFixed(2)}</td>
                    <td>${sale.payment_method || ''}</td>
                </tr>`;
            });
            
            list.innerHTML = html;
                
            // 更新分页控件
            updateTaxPagination(
                document.getElementById('tax-pagination'),
                page,
                response.pagination.total_pages,
                startDate,
                endDate,
                paymentMethod,
                rate
            );
        })
        .catch(err => {
            console.error('加载税务数据失败', err);
            document.getElementById('tax-list').innerHTML = `<tr><td colspan="8" class="error-message">加载失败：${err.message}</td></tr>`;
            document.getElementById('tax-pagination').innerHTML = '';
        });
}

// 税务管理分页控件更新
function updateTaxPagination(container, currentPage, totalPages, startDate, endDate, paymentMethod, rate) {
    if (totalPages <= 1) {
        container.innerHTML = '';
        return;
    }
    
    let html = '<div class="pagination">';
    
    // 上一页按钮
    html += `
        <button class="pagination-btn ${currentPage === 1 ? 'disabled' : ''}" 
            ${currentPage === 1 ? 'disabled' : `onclick="loadTaxData(${currentPage - 1})"`}>
            上一页
        </button>
    `;
    
    // 页码按钮
    const maxVisiblePages = 5;
    let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
    let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);
    
    if (endPage - startPage + 1 < maxVisiblePages) {
        startPage = Math.max(1, endPage - maxVisiblePages + 1);
    }
    
    if (startPage > 1) {
        html += `
            <button class="pagination-btn" onclick="loadTaxData(1)">1</button>
            ${startPage > 2 ? '<span class="pagination-ellipsis">...</span>' : ''}
        `;
    }
    
    for (let i = startPage; i <= endPage; i++) {
        html += `
            <button class="pagination-btn ${i === currentPage ? 'active' : ''}" 
                onclick="loadTaxData(${i})">
                ${i}
            </button>
        `;
    }
    
    if (endPage < totalPages) {
        html += `
            ${endPage < totalPages - 1 ? '<span class="pagination-ellipsis">...</span>' : ''}
            <button class="pagination-btn" onclick="loadTaxData(${totalPages})">
                ${totalPages}
            </button>
        `;
    }
    
    // 下一页按钮
    html += `
        <button class="pagination-btn ${currentPage === totalPages ? 'disabled' : ''}"
            ${currentPage === totalPages ? 'disabled' : `onclick="loadTaxData(${currentPage + 1})"`}>
            下一页
        </button>
    `;
    
    // 页码信息
    html += `
        <span class="pagination-info">第 ${currentPage}/${totalPages} 页，共 ${totalPages} 页</span>
    `;
    
    html += '</div>';
    container.innerHTML = html;
}

// 添加导出功能
function exportTaxData() {
    const startDate = document.getElementById('tax-start-date').value;
    const endDate = document.getElementById('tax-end-date').value;
    const rate = parseFloat(document.getElementById('tax-rate').value) || 0;
    
    // 获取表格行
    const rows = document.querySelectorAll('#tax-list tr');
    if (!rows.length || rows[0].classList.contains('no-data')) {
        showNotification('暂无数据可导出', 'warning');
        return;
    }
    
    // 构建CSV内容
    let csv = '订单号,日期,商品信息,总数量,单价,订单总额,税额,支付方式\n';
    rows.forEach(row => {
        const cols = row.querySelectorAll('td');
        if (cols.length === 8) {
            const values = Array.from(cols).map(cell => cell.textContent.replace('¥', '').trim());
            csv += values.join(',') + '\n';
        }
    });
    
    // 触发下载
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `税务报表_${startDate}_${endDate}.csv`;
    link.click();
    URL.revokeObjectURL(link.href);
    showNotification('导出成功', 'success');
}

// 从HTML文件加载模块内容的通用函数
function loadModuleFromHTML(moduleName) {
    fetch(`modules/${moduleName}.html`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`模块加载失败: ${response.statusText}`);
            }
            return response.text();
        })
        .then(htmlContent => {
            // 注入模块HTML
            moduleContent.innerHTML = htmlContent;
            // 执行内联脚本
            moduleContent.querySelectorAll('script').forEach(script => {
                if (!script.src && script.textContent) {
                    try {
                        eval(script.textContent);
                    } catch (e) {
                        console.error('模块脚本执行失败:', e);
                    }
                }
            });
            // 通知模块加载完成
            document.dispatchEvent(new CustomEvent('moduleLoaded', { detail: { module: moduleName } }));
        })
        .catch(error => {
            console.error(`加载模块 ${moduleName} 失败:`, error);
            moduleContent.innerHTML = `
                <div class="error-message">
                    <h2>模块加载失败</h2>
                    <p>${error.message}</p>
                </div>`;
        });
}

// 在末尾添加供应商模块初始化及 CRUD 逻辑
// 监听模块加载事件
document.addEventListener('moduleLoaded', event => {
    if (event.detail.module === 'supplier-info') {
        initSupplierModule();
    }
    if (event.detail.module === 'member-points') {
        initMemberPointsModule();
    }
    if (event.detail.module === 'purchase-order') {
        initPurchaseOrderModule();
    }
});

function initPurchaseOrderModule() {
    let suppliers = [];
    let products = [];
    let purchaseOrderList = []; // 新增：保存所有订单数据
    // 拉取供应商和商品数据
    fetch('/api/suppliers').then(res=>res.json()).then(data=>{
        if(data.success && Array.isArray(data.data)){
            suppliers = data.data;
            fillSupplierSelect();
        }
    });
    fetch('/api/products').then(res=>res.json()).then(data=>{
        if(data.success && Array.isArray(data.data)){
            products = data.data;
        }
    });

    // 填充供应商下拉
    function fillSupplierSelect() {
        const sel = document.getElementById('supplier-select');
        if (!sel) return;
        sel.innerHTML = '<option value="">请选择供应商</option>';
        suppliers.forEach(sup => {
            sel.innerHTML += `<option value="${sup.name}">${sup.name}</option>`;
        });
    }

    // 商品明细行渲染
    function createProductRow(item = {}) {
        const row = document.createElement('div');
        row.className = 'goods-item-row';
        row.innerHTML = `
            <select class="order-product-select form-control">
                <option value="">请选择商品</option>
                ${products.map(p=>`<option value="${p.product_code}" ${item.product_code===p.product_code?'selected':''}>${p.product_name}</option>`).join('')}
            </select>
            <input type="number" class="order-qty-input form-control" min="1" value="${item.quantity||1}">
            <input type="number" class="order-price-input form-control" min="0.01" step="0.01" value="${item.unit_price||''}" placeholder="单价">
            <span class="item-amount">0.00</span>
            <button type="button" class="remove-order-item-btn" style="background:#ef4444;color:white;border:none;border-radius:4px;padding:4px 10px;">删除</button>
        `;
        // 删除按钮
        row.querySelector('.remove-order-item-btn').onclick = ()=>{ row.remove(); calcTotal(); };
        // 商品选择联动单价
        const prodSel = row.querySelector('.order-product-select');
        const priceInput = row.querySelector('.order-price-input');
        prodSel.onchange = function(){
            const prod = products.find(p=>p.product_code===this.value);
            if(prod) priceInput.value = prod.price;
            calcRowAmount();
            calcTotal();
        };
        // 数量/单价变化联动金额
        row.querySelector('.order-qty-input').oninput = calcRowAmount;
        priceInput.oninput = calcRowAmount;
        function calcRowAmount(){
            const qty = parseFloat(row.querySelector('.order-qty-input').value)||0;
            const price = parseFloat(priceInput.value)||0;
            row.querySelector('.item-amount').textContent = (qty*price).toFixed(2);
            calcTotal();
        }
        calcRowAmount();
        return row;
    }

    // 绑定添加商品按钮
    const addBtn = document.getElementById('add-order-item-btn');
    const itemsContainer = document.getElementById('order-items-container');
    if(addBtn && itemsContainer){
        addBtn.onclick = function(){
            itemsContainer.appendChild(createProductRow());
        };
    }
    // 计算总金额
    function calcTotal(){
        let total = 0;
        itemsContainer.querySelectorAll('.goods-item-row').forEach(row=>{
            const qty = parseFloat(row.querySelector('.order-qty-input').value)||0;
            const price = parseFloat(row.querySelector('.order-price-input').value)||0;
            total += qty*price;
        });
        document.getElementById('total-amount').textContent = total.toFixed(2);
    }
    // 表单提交
const form = document.getElementById('purchase-order-form');
if(form){
    form.onsubmit = function(e){
        e.preventDefault();
        // 获取表单数据
        const supplier = document.getElementById('supplier-select').value;
        const order_date = document.getElementById('order-date').value;
        const expected_date = document.getElementById('expected-date').value;
        // 获取商品明细
        const items = [];
        let valid = true;
        itemsContainer.querySelectorAll('.goods-item-row').forEach(row=>{
            const prodSel = row.querySelector('.order-product-select');
            const qtyInput = row.querySelector('.order-qty-input');
            const priceInput = row.querySelector('.order-price-input');
            const product_code = prodSel.value;
            const product = products.find(p=>p.product_code===product_code);
            const product_name = product ? product.product_name : '';
            const quantity = parseFloat(qtyInput.value)||0;
            const unit_price = parseFloat(priceInput.value)||0;
            if(!product_code || quantity<=0 || unit_price<=0){
                valid = false;
            }
            items.push({product_code, product_name, quantity, unit_price});
        });
        if(!supplier || !order_date || items.length===0 || !valid){
            alert('请完整填写订单信息和商品明细');
            return;
        }
        // 提交到后端
        fetch('/api/purchase-orders',{
            method:'POST',
            headers:{'Content-Type':'application/json'},
            body:JSON.stringify({supplier, order_date, expected_date, items})
        }).then(res=>res.json()).then(data=>{
            if(data.success){
                alert('采购订单提交成功！');
                form.reset();
                itemsContainer.innerHTML = '';
                itemsContainer.appendChild(createProductRow());
                document.getElementById('total-amount').textContent = '0.00';
                loadOrderList();
            }else{
                alert('提交失败：'+data.message);
            }
        }).catch(err=>{
            alert('提交失败，请检查网络');
        });
    };
}

// 加载订单列表
function loadOrderList(){
    fetch('/api/purchase-orders').then(res=>res.json()).then(data=>{
        if(data.success && Array.isArray(data.data)){
            purchaseOrderList = data.data;
            renderOrderList(purchaseOrderList);
        }else{
            const list = document.getElementById('purchase-order-list');
            if(list) list.innerHTML = '<tr><td colspan="7" class="no-data">暂无订单</td></tr>';
        }
    });
}
// 渲染订单列表，支持传入过滤后的list
function renderOrderList(list){
    const tbody = document.getElementById('purchase-order-list');
    if(!tbody) return;
    if(!list || !list.length){
        tbody.innerHTML = '<tr><td colspan="7" class="no-data">暂无订单</td></tr>';
        return;
    }
    tbody.innerHTML = list.map(order=>`
        <tr>
            <td>${order.order_number}</td>
            <td>${order.supplier}</td>
            <td>${order.order_date}</td>
            <td>¥${parseFloat(order.total_amount).toFixed(2)}</td>
            <td><span class="status-badge ${order.status==='pending'?'status-pending':'status-completed'}">${order.status==='pending'?'处理中':'已完成'}</span></td>
            <td style="text-align:right;">
                <button class="action-btn btn-export" data-no="${order.order_number}" title="导出"><i class="fas fa-print"></i></button>
                <button class="action-btn btn-detail" data-no="${order.order_number}" title="详情"><i class="fas fa-file-alt"></i></button>
                <button class="action-btn btn-status" data-no="${order.order_number}" data-status="${order.status}" title="切换状态"><i class="fas fa-edit"></i></button>
                <button class="action-btn btn-delete" data-no="${order.order_number}" title="删除" style="color:#ef4444;"><i class="fas fa-trash"></i></button>
            </td>
        </tr>
    `).join('');
    // 绑定导出
    tbody.querySelectorAll('.btn-export').forEach(btn=>{
        btn.onclick = function(){
            const no = btn.getAttribute('data-no');
            window.open(`/api/purchase-orders/${no}/export`, '_blank');
        };
    });
    // 绑定详情
    tbody.querySelectorAll('.btn-detail').forEach(btn=>{
        btn.onclick = function(){
            const no = btn.getAttribute('data-no');
            fetch(`/api/purchase-orders/${no}`).then(res=>res.json()).then(data=>{
                if(data.success){
                    const order = data.data.order;
                    const items = data.data.items;
                    let html = `<h3>订单号：${order.order_number}</h3><p>供应商：${order.supplier}</p><p>订单日期：${order.order_date}</p><p>预计到货：${order.expected_date||''}</p><p>总金额：¥${order.total_amount}</p><p>状态：${order.status==='pending'?'处理中':'已完成'}</p>`;
                    html += '<table class="data-table"><thead><tr><th>商品编码</th><th>商品名称</th><th>数量</th><th>单价</th></tr></thead><tbody>';
                    html += items.map(it=>`<tr><td>${it.product_code}</td><td>${it.product_name}</td><td>${it.quantity}</td><td>¥${it.unit_price}</td></tr>`).join('');
                    html += '</tbody></table>';
                    // 简单弹窗
                    const modal = document.createElement('div');
                    modal.style.position = 'fixed';
                    modal.style.left = '0';
                    modal.style.top = '0';
                    modal.style.width = '100vw';
                    modal.style.height = '100vh';
                    modal.style.background = 'rgba(0,0,0,0.3)';
                    modal.style.zIndex = '9999';
                    modal.innerHTML = `<div style="background:#fff;max-width:600px;margin:5vh auto;padding:2rem;border-radius:10px;position:relative;">${html}<button style="position:absolute;top:10px;right:10px;" onclick="this.closest('div').parentNode.remove()">关闭</button></div>`;
                    document.body.appendChild(modal);
                }else{
                    showNotification('获取详情失败', 'error');
                }
            });
        };
    });
    // 绑定状态切换
    tbody.querySelectorAll('.btn-status').forEach(btn=>{
        btn.onclick = function(){
            const no = btn.getAttribute('data-no');
            const cur = btn.getAttribute('data-status');
            const next = cur==='pending'?'completed':'pending';
            fetch(`/api/purchase-orders/${no}`,{
                method:'PUT',
                headers:{'Content-Type':'application/json'},
                body:JSON.stringify({status:next})
            }).then(res=>res.json()).then(data=>{
                if(data.success){
                    showNotification('状态更新成功', 'success');
                    loadOrderList();
                }else{
                    showNotification('状态更新失败', 'error');
                }
            });
        };
    });
    // 绑定删除
    tbody.querySelectorAll('.btn-delete').forEach(btn=>{
        btn.onclick = function(){
            const no = btn.getAttribute('data-no');
            if(confirm('确定要删除该订单吗？')){
                fetch(`/api/purchase-orders/${no}`, {method:'DELETE'}).then(res=>res.json()).then(data=>{
                    if(data.success){
                        showNotification('删除成功', 'success');
                        loadOrderList();
                    }else{
                        showNotification('删除失败：'+data.message, 'error');
                    }
                }).catch(()=>{
                    showNotification('删除失败，网络错误', 'error');
                });
            }
        };
    });
}
// 搜索功能
const searchInput = document.getElementById('order-search');
if(searchInput){
    searchInput.addEventListener('input', function(){
        const keyword = this.value.trim();
        if(!keyword){
            renderOrderList(purchaseOrderList);
            return;
        }
        const filtered = purchaseOrderList.filter(order =>
            (order.order_number && order.order_number.includes(keyword)) ||
            (order.supplier && order.supplier.includes(keyword))
        );
        renderOrderList(filtered);
    });
}
// 页面初始化时加载订单列表
loadOrderList();
}
// 初始化供应商模块
function initSupplierModule() {
    let editId = null;

    const form = document.getElementById('supplier-form');
    const nameInput = document.getElementById('supplier-name');
    const contactInput = document.getElementById('supplier-contact');
    const phoneInput = document.getElementById('supplier-phone');
    const regionInput = document.getElementById('supplier-region');
    const addressInput = document.getElementById('supplier-address');
    const searchBtn = document.getElementById('search-btn');
    const resetBtn = document.getElementById('reset-btn');

    // 重置表单到新增状态
    function resetForm() {
        editId = null;
        form.reset();
        form.querySelector('.btn-save').textContent = '';
        form.querySelector('.btn-save').innerHTML = '<i class="fas fa-save"></i> 保存';
    }

    // 加载并渲染供应商列表
    function loadSupplierList() {
        fetch('/api/suppliers')
            .then(res => res.json())
            .then(response => {
                if (!response.success) throw new Error(response.message);
                const data = response.data;
                // 更新统计
                document.getElementById('total-suppliers').textContent = data.length;
                // 本月新增
                const month = new Date().toISOString().slice(0,7);
                const newCount = data.filter(s => s.create_time && s.create_time.slice(0,7) === month).length;
                document.getElementById('new-suppliers').textContent = newCount;
                // 不支持删除统计，暂为0
                document.getElementById('removed-suppliers').textContent = 0;
                // 渲染表格
                renderSupplierTable(data);
            })
            .catch(err => {
                showNotification('加载供应商列表失败：' + err.message, 'error');
            });
    }

    // 渲染表格
    function renderSupplierTable(list) {
        const tbody = document.getElementById('supplier-list');
        if (!list.length) {
            tbody.innerHTML = '<tr><td colspan="5" class="no-data">暂无数据</td></tr>';
            return;
        }
        tbody.innerHTML = list.map(item => `
            <tr data-id="${item.id}">
                <td>${item.name}</td>
                <td>${item.contact || '-'}</td>
                <td>${item.phone || '-'}</td>
                <td>${item.address || '-'}</td>
                <td>
                    <button class="btn-edit btn-icon"><i class="fas fa-edit"></i></button>
                    <button class="btn-delete btn-icon"><i class="fas fa-trash"></i></button>
                </td>
            </tr>
        `).join('');

        // 绑定编辑和删除
        tbody.querySelectorAll('.btn-edit').forEach(btn => {
            btn.addEventListener('click', () => {
                const tr = btn.closest('tr');
                const id = tr.getAttribute('data-id');
                // 获取当前行数据
                fetch(`/api/suppliers`).then(res => res.json()).then(resp => {
                    const sup = resp.data.find(s => s.id == id);
                    if (sup) {
                        editId = id;
                        nameInput.value = sup.name;
                        contactInput.value = sup.contact || '';
                        phoneInput.value = sup.phone || '';
                        addressInput.value = sup.address || '';
                        // 改为编辑保存
                        form.querySelector('.btn-save').innerHTML = '<i class="fas fa-save"></i> 更新';
                    }
                });
            });
        });
        tbody.querySelectorAll('.btn-delete').forEach(btn => {
            btn.addEventListener('click', () => {
                const tr = btn.closest('tr');
                const id = tr.getAttribute('data-id');
                if (confirm('确定删除该供应商？')) {
                    fetch(`/api/suppliers/${id}`, { method: 'DELETE' })
                        .then(res => res.json())
                        .then(resp => {
                            if (resp.success) {
                                showNotification('删除成功', 'success');
                                loadSupplierList();
                            } else {
                                showNotification('删除失败：' + resp.message, 'error');
                            }
                        });
                }
            });
        });
    }

    // 表单提交
    form.addEventListener('submit', e => {
        e.preventDefault();
        const payload = {
            name: nameInput.value,
            contact: contactInput.value,
            phone: phoneInput.value,
            address: addressInput.value
        };
        const url = editId ? `/api/suppliers/${editId}` : '/api/suppliers';
        const method = editId ? 'PUT' : 'POST';
        fetch(url, {
            method,
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
        })
        .then(res => res.json())
        .then(resp => {
            if (resp.success) {
                showNotification(editId ? '更新成功' : '添加成功', 'success');
                resetForm();
                loadSupplierList();
            } else {
                showNotification('操作失败：' + resp.message, 'error');
            }
        })
        .catch(err => showNotification('请求失败：' + err.message, 'error'));
    });

    // 搜索
    searchBtn.addEventListener('click', () => {
        const term = document.getElementById('search-input').value.toLowerCase();
        // 本地过滤
        fetch('/api/suppliers').then(res=>res.json()).then(resp=>{
            let data = resp.success ? resp.data : [];
            if (term) data = data.filter(s => s.name.toLowerCase().includes(term));
            renderSupplierTable(data);
        });
    });
    // 重置
    resetBtn.addEventListener('click', () => {
        document.getElementById('search-input').value = '';
        resetForm();
        loadSupplierList();
    });

    // 初始加载
    resetForm();
    loadSupplierList();
}

// 初始化会员积分兑换模块
function initMemberPointsModule() {
    const memberSearchInput = document.getElementById('member-search');
    const memberInfoEl = document.getElementById('member-info');
    const productSelect = document.getElementById('product-select');
    const qtyInput = document.getElementById('redeem-qty');
    const currentPointsEl = document.getElementById('current-points');
    const requiredPointsEl = document.getElementById('required-points');
    const afterPointsEl = document.getElementById('after-points');
    const form = document.getElementById('redeem-form');
    const detailsTbody = document.querySelector('.data-table tbody');

    // 定义可兑换商品积分消耗
    const redeemCosts = { '可乐':50, '雪碧':50, '抽纸':30, '食用油':200, '洗发水':150, '牙膏':80 };
    // 设置默认积分消耗（每元价格兑换10积分）
    const defaultPointRate = 10;
    
    // 用于存储自定义积分设置
    let customPointsSettings = {};
    
    // 当前会员
    let currentMember = null;

    // 加载可兑换商品
    fetch('/api/products/exchange')
        .then(res => res.json())
        .then(resp => {
            if (!resp.success) throw new Error(resp.message);
            resp.data.forEach(prod => {
                if ((redeemCosts[prod.product_name] || prod.price > 0) && prod.current_stock > 0) {
                    const option = document.createElement('option');
                    option.value = prod.product_code;
                    option.textContent = `${prod.product_name} (${prod.current_stock} 库存)`;
                    option.dataset.price = prod.price;
                    productSelect.appendChild(option);
                }
            });
        })
        .catch(err => showNotification('加载可兑换商品失败: '+err.message,'error'));

    // 会员搜索
    memberSearchInput.addEventListener('change', () => {
        const phone = memberSearchInput.value.trim();
        if (!phone) return;
        fetch(`/api/members/phone/${phone}`)
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    currentMember = data.data;
                    memberInfoEl.textContent = `${currentMember.name} (${currentMember.member_code}), 积分: ${currentMember.points}`;
                    currentPointsEl.value = currentMember.points;
                    updateRequiredAndAfter();
                    
                    // 加载该会员的积分明细记录
                    loadMemberPointRecords(currentMember.member_code);
                } else {
                    showNotification('未找到会员','error');
                    currentMember = null;
                    memberInfoEl.textContent = '';
                    currentPointsEl.value = '';
                    requiredPointsEl.value = '';
                    afterPointsEl.value = '';
                    // 清空积分明细表格
                    detailsTbody.innerHTML = '<tr><td colspan="6" style="text-align:center;">请先选择会员</td></tr>';
                }
            });
    });
    
    // 加载会员积分记录
    function loadMemberPointRecords(memberCode) {
        fetch(`/api/members/${memberCode}/point-records`)
            .then(res => res.json())
            .then(resp => {
                if (resp.success) {
                    updatePointRecordsTable(resp.data);
                } else {
                    showNotification('加载积分记录失败: ' + resp.message, 'error');
                }
            })
            .catch(err => {
                showNotification('加载积分记录失败: ' + err.message, 'error');
            });
    }
    
    // 更新积分记录表格
    function updatePointRecordsTable(records) {
        if (!records || records.length === 0) {
            detailsTbody.innerHTML = '<tr><td colspan="4" style="text-align:center;">暂无积分记录</td></tr>';
            return;
        }
        
        detailsTbody.innerHTML = '';
        records.forEach(record => {
            const row = document.createElement('tr');
            
            // 确定积分显示格式
            let pointsDisplay;
            if (record.record_type === 'earn') {
                pointsDisplay = `<span style="color:#22c55e;font-weight:500">+${record.points}</span>`;
            } else {
                pointsDisplay = `<span style="color:#ef4444;font-weight:500">-${record.points}</span>`;
            }
            
            // 获取会员剩余积分（模拟计算，实际应从API获取）
            // 假设records是按时间降序排序的
            const memberPointsBeforeRecord = record.record_type === 'earn' 
                ? currentMember.points - record.points
                : currentMember.points + record.points;
            
            row.innerHTML = `
                <td>${record.create_time || record.record_date}</td>
                <td>${record.member_name} (${record.member_code})</td>
                <td>${pointsDisplay}</td>
                <td>${record.record_type === 'earn' ? currentMember.points : memberPointsBeforeRecord}</td>
            `;
            detailsTbody.appendChild(row);
        });
    }

    productSelect.addEventListener('change', updateRequiredAndAfter);
    qtyInput.addEventListener('input', updateRequiredAndAfter);

    // 提交兑换请求
    form.addEventListener('submit', e => {
        e.preventDefault();
        if (!currentMember) { showNotification('请先输入并确认会员','warning'); return; }
        const prodCode = productSelect.value;
        if (!prodCode) { showNotification('请选择商品','warning'); return; }
        const qty = parseInt(qtyInput.value) || 1;
        const productOption = productSelect.querySelector(`option[value="${prodCode}"]`);
        const prodName = productOption.textContent.split(' ')[0];
        
        // 计算所需积分：优先使用自定义积分设置，其次预设积分，最后按商品价格计算
        let pointsPerUnit;
        if (productOption.dataset.points) {
            pointsPerUnit = parseInt(productOption.dataset.points);
        } else if (customPointsSettings[prodCode]) {
            pointsPerUnit = customPointsSettings[prodCode];
        } else if (redeemCosts[prodName]) {
            pointsPerUnit = redeemCosts[prodName];
        } else {
            pointsPerUnit = Math.round(parseFloat(productOption.dataset.price) * defaultPointRate);
        }
        
        const totalCost = pointsPerUnit * qty;
        
        if (currentMember.points < totalCost) { 
            showNotification('积分不足','error'); 
            return; 
        }
        
        // 显示加载状态
        const submitBtn = form.querySelector('button[type="submit"]');
        const originalBtnText = submitBtn.innerHTML;
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 处理中...';
        
        // 发送API请求
        fetch('/api/redeem', {
            method:'POST',
            headers:{'Content-Type':'application/json'},
            body: JSON.stringify({ 
                member_code: currentMember.member_code, 
                product_code: prodCode, 
                quantity: qty,
                points_cost: totalCost  // 传递自定义积分值
            })
        })
        .then(res => res.json())
        .then(resp => {
            if (resp.success) {
                showNotification('兑换成功','success');
                
                // 更新会员信息
                currentMember = resp.data.member;
                currentPointsEl.value = currentMember.points;
                memberInfoEl.textContent = `${currentMember.name} (${currentMember.member_code}), 积分: ${currentMember.points}`;
                
                // 更新积分明细表格
                if (resp.data.recent_records && resp.data.recent_records.length > 0) {
                    // 使用API返回的最新记录
                    updatePointRecordsTable(resp.data.recent_records);
                } else {
                    // 如果API没有返回记录，手动添加一条
                    const record = resp.data.record;
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${record.create_time || record.record_date}</td>
                        <td>${currentMember.name} (${currentMember.member_code})</td>
                        <td style="color:#ef4444;font-weight:500">-${totalCost}</td>
                        <td>${currentMember.points}</td>`;
                    
                    // 将新记录插入表格的最上方
                    if (detailsTbody.firstChild) {
                        detailsTbody.insertBefore(row, detailsTbody.firstChild);
                    } else {
                        detailsTbody.appendChild(row);
                    }
                }
                
                // 更新库存显示
                const newStock = resp.data.product.current_stock;
                productOption.textContent = `${prodName} (${newStock} 库存)`;
                if (newStock <= 0) productSelect.removeChild(productOption);
                
                // 重置数量
                qtyInput.value = 1;
                requiredPointsEl.value = '';
                afterPointsEl.value = '';
            } else {
                showNotification(resp.message,'error');
            }
        })
        .catch(err => showNotification('兑换失败: '+err.message,'error'))
        .finally(() => {
            // 恢复按钮状态
            submitBtn.disabled = false;
            submitBtn.innerHTML = originalBtnText;
        });
    });
    
    // ... 其余代码保持不变 ...
    
    // 绑定"从库存添加商品"按钮点击事件
    const addBtn = document.getElementById('add-redeem-product-btn');
    if (addBtn) {
        addBtn.addEventListener('click', () => {
            const modal = document.getElementById('redeem-modal');
            const listContainer = document.getElementById('redeem-modal-list');
            listContainer.innerHTML = '<div style="text-align:center;padding:20px;">正在加载商品列表...</div>';
            modal.style.display = 'flex';
            
            // 加载并渲染库存商品表格
            fetch('/api/products/exchange')
                .then(res => res.json())
                .then(resp => {
                    if (!resp.success) throw new Error(resp.message);
                    if (resp.data.length === 0) {
                        listContainer.innerHTML = '<div style="text-align:center;padding:20px;">没有可用的库存商品</div>';
                        return;
                    }
                    
                    // 构建商品列表HTML
                    const rows = resp.data
                        .map(prod => {
                            // 计算所需积分
                            let points;
                            if (customPointsSettings[prod.product_code]) {
                                points = customPointsSettings[prod.product_code];
                            } else if (redeemCosts[prod.product_name]) {
                                points = redeemCosts[prod.product_name];
                            } else {
                                points = Math.round((prod.price || 0) * defaultPointRate);
                            }
                            
                            return `
                                <tr data-product-code="${prod.product_code}" class="product-row">
                                    <td style="text-align:center;"><input type="checkbox" value="${prod.product_code}" data-name="${prod.product_name}" data-stock="${prod.current_stock}" data-price="${prod.price || 0}" data-points="${points}" /></td>
                                    <td style="padding:8px;">${prod.product_name}</td>
                                    <td style="text-align:center;">${prod.current_stock}</td>
                                    <td class="points-cell" style="text-align:center;">${points}</td>
                                    <td style="text-align:center;">
                                        <button type="button" class="edit-points-btn" style="background:#3b82f6;color:white;border:none;border-radius:4px;padding:6px 12px;cursor:pointer;">
                                            修改积分
                                        </button>
                                    </td>
                                </tr>
                            `;
                        }).join('');
                    
                    // 添加搜索框和表格
                    listContainer.innerHTML = `
                        <div style="margin-bottom:15px;">
                            <input type="text" id="product-search" placeholder="搜索商品名称..." style="width:100%; padding:10px; border:1px solid #e2e8f0; border-radius:6px;">
                        </div>
                        <table class="data-table" style="width:100%; border-collapse:collapse;">
                            <thead>
                                <tr>
                                    <th style="width:5%;"></th>
                                    <th style="width:40%;">商品名称</th>
                                    <th style="width:15%; text-align:center;">库存数量</th>
                                    <th style="width:15%; text-align:center;">所需积分</th>
                                    <th style="width:25%; text-align:center;">操作</th>
                                </tr>
                            </thead>
                            <tbody id="products-tbody">${rows}</tbody>
                        </table>`;
                        
                    // 绑定搜索框事件
                    const searchInput = document.getElementById('product-search');
                    searchInput.addEventListener('input', function() {
                        const query = this.value.toLowerCase().trim();
                        const tbody = document.getElementById('products-tbody');
                        const productRows = tbody.querySelectorAll('.product-row');
                        
                        productRows.forEach(row => {
                            const productName = row.querySelector('td:nth-child(2)').textContent.toLowerCase();
                            if (productName.includes(query)) {
                                row.style.display = '';
                            } else {
                                row.style.display = 'none';
                            }
                        });
                    });
                    
                    // 绑定修改积分按钮事件
                    listContainer.querySelectorAll('.edit-points-btn').forEach(btn => {
                        btn.addEventListener('click', (e) => {
                            const row = e.target.closest('tr');
                            const productCode = row.dataset.productCode;
                            const pointsCell = row.querySelector('.points-cell');
                            const currentPoints = parseInt(pointsCell.textContent);
                            
                            // 创建编辑界面
                            const input = document.createElement('input');
                            input.type = 'number';
                            input.min = '1';
                            input.value = currentPoints;
                            input.style.width = '60px';
                            
                            const saveBtn = document.createElement('button');
                            saveBtn.textContent = '保存';
                            saveBtn.className = 'save-points-btn';
                            saveBtn.style.background = '#22c55e';
                            saveBtn.style.color = 'white';
                            saveBtn.style.border = 'none';
                            saveBtn.style.borderRadius = '4px';
                            saveBtn.style.padding = '4px 8px';
                            saveBtn.style.marginLeft = '5px';
                            saveBtn.style.cursor = 'pointer';
                            
                            const cancelBtn = document.createElement('button');
                            cancelBtn.textContent = '取消';
                            cancelBtn.className = 'cancel-edit-btn';
                            cancelBtn.style.background = '#94a3b8';
                            cancelBtn.style.color = 'white';
                            cancelBtn.style.border = 'none';
                            cancelBtn.style.borderRadius = '4px';
                            cancelBtn.style.padding = '4px 8px';
                            cancelBtn.style.marginLeft = '5px';
                            cancelBtn.style.cursor = 'pointer';
                            
                            // 清空单元格并添加编辑控件
                            pointsCell.textContent = '';
                            pointsCell.appendChild(input);
                            pointsCell.appendChild(saveBtn);
                            pointsCell.appendChild(cancelBtn);
                            
                            // 隐藏修改按钮
                            e.target.style.display = 'none';
                            
                            // 绑定保存按钮事件
                            saveBtn.addEventListener('click', () => {
                                const newPoints = parseInt(input.value);
                                if (isNaN(newPoints) || newPoints < 1) {
                                    showNotification('请输入有效的积分值', 'warning');
                                    return;
                                }
                                
                                // 保存新的积分值
                                customPointsSettings[productCode] = newPoints;
                                pointsCell.textContent = newPoints;
                                
                                // 更新复选框的积分数据
                                const checkbox = row.querySelector('input[type="checkbox"]');
                                if (checkbox) {
                                    checkbox.dataset.points = newPoints;
                                }
                                
                                // 显示修改按钮
                                e.target.style.display = 'inline-block';
                                
                                showNotification('积分修改成功', 'success');
                            });
                            
                            // 绑定取消按钮事件
                            cancelBtn.addEventListener('click', () => {
                                pointsCell.textContent = currentPoints;
                                // 显示修改按钮
                                e.target.style.display = 'inline-block';
                            });
                            
                            // 自动聚焦到输入框
                            input.focus();
                        });
                    });
                })
                .catch(err => {
                    listContainer.innerHTML = `<div style="text-align:center;padding:20px;color:#f44336;">加载失败: ${err.message}</div>`;
                    showNotification('加载库存商品失败: ' + err.message, 'error');
                });
            const confirmBtn = document.getElementById('redeem-modal-confirm');
            const cancelBtn = document.getElementById('redeem-modal-cancel');
            if (confirmBtn && cancelBtn) {
                confirmBtn.onclick = () => {
                    const checks = listContainer.querySelectorAll('input[type="checkbox"]:checked');
                    if (checks.length === 0) {
                        showNotification('请至少选择一个商品', 'warning');
                        return;
                    }
                    
                    let addedCount = 0;
                    checks.forEach(cb => {
                        const code = cb.value, name = cb.dataset.name, stock = cb.dataset.stock, price = cb.dataset.price;
                        const points = cb.dataset.points || Math.round(price * defaultPointRate);
                        
                        if (!productSelect.querySelector(`option[value=\"${code}\"]`)) {
                            const opt = document.createElement('option');
                            opt.value = code;
                            opt.textContent = `${name} (${stock} 库存)`;
                            opt.dataset.price = price;
                            opt.dataset.points = points; // 保存积分信息
                            productSelect.appendChild(opt);
                            addedCount++;
                            
                            // 保存自定义积分设置
                            customPointsSettings[code] = parseInt(points);
                        }
                    });
                    
                    if (addedCount > 0) {
                        showNotification(`成功添加${addedCount}个商品到兑换列表`, 'success');
                    } else {
                        showNotification('所选商品已在兑换列表中', 'info');
                    }
                    
                    modal.style.display = 'none';
                };
                cancelBtn.onclick = () => { modal.style.display = 'none'; };
            }
        });
    }
    
    function updateRequiredAndAfter() {
        const prodCode = productSelect.value;
        const qty = parseInt(qtyInput.value) || 1;
        if (!prodCode || !currentMember) return;
        const productOption = productSelect.querySelector(`option[value="${prodCode}"]`);
        const prodName = productOption.textContent.split(' ')[0];
        
        // 使用自定义积分设置或默认计算方法
        let pointsPerUnit;
        if (productOption.dataset.points) {
            pointsPerUnit = parseInt(productOption.dataset.points);
        } else if (customPointsSettings[prodCode]) {
            pointsPerUnit = customPointsSettings[prodCode];
        } else if (redeemCosts[prodName]) {
            pointsPerUnit = redeemCosts[prodName];
        } else {
            pointsPerUnit = Math.round(parseFloat(productOption.dataset.price) * defaultPointRate);
        }
        
        const cost = pointsPerUnit * qty;
        requiredPointsEl.value = cost;
        afterPointsEl.value = currentMember.points - cost;
    }
}
